Skip to main content

Section 5.3 Returning

Now we are ready to worry about how a function like doubleValue does its work. The body of a function Is the statements that are in curly braces after the functions prototype. They are the code that runs when the function is called. As a reminder, here is the body of the doubleValue function with its body highlighted:
int doubleValue(int num) {
    int result = 2 * num;
    return result;
}
On the first line of the body (line 2), the function takes the parameter num and multiplies it by 2. From inside the function, the parameters work just like variables that have been already set before the function body starts running. The values any parameters are set to are determined by what was passed in by the caller.
The last line of the function is a return statement. The return keyword essentially says: β€œreturn immediately from this function. Give this value back to the code that called the function.” Following the return is the value to be returned. It can be a single variable, or an expression that will be evaluated before it is returned.

Warning 5.3.1.

Returning a value is how a function fulfills the promise made by its return type. This function promises it returns an int, so it must end by retuning a value that is an integer. If a function fails to return the right kind of data it will be a compile error or a warning.
Once a return is hit, execution leaves the function. Nothing that comes after the return will get to run!
Watching functions run in the Codelens can help you see how information moves into and out of the function:
Listing 5.3.1.
Step The code line by line. Notice that as you reach the doubleValue in main the next line that executes is the double value function. As that function starts running, the parameter num is automatically set to the value that was passed in from main (the value x has, which is 5). When we reach the return execution jumps back to where the function call was and the returned result is stored into the variable y.
Here is a program that uses the function twice. Again, try running it in Codelens:
Listing 5.3.2.
Notice that both times we reach a call to doubleValue in main, we jump up to the function. The num parameter is set to a different value in each call. When the function finishes and returns, the returned value goes back to the place where the function was most recently called from and execution resumes from there.

Checkpoint 5.3.1.

You have attempted of activities on this page.