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.
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.
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.
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.