Section4.2Parameter Passing: by Value versus by Reference
In all of the functions we have written thus far, we have used a function calling mechanism called pass by value. Calling a function by value involves copying the contents of the arguments into the memory locations of the corresponding formal parameters. If the function changes the values of the parameters, the original contents in the memory referenced by the arguments of the calling function do not change.
void functionExample( int inputVar ) { /*return type void which indicates that
nothing is being returned*/
int nextVar = inputVar * 2;
inputVar = 4;
cout << "nextVar = " << nextVar << " inputVar = " << inputVar;
}
void callingFunction() { /*return type void which indicates
that nothing is being returned*/
int myVar = 10;
functionExample( myVar );
cout << "myVar = " << myVar;
}
When the function callingFunction() executes, it calls functionExample(...) with the variable myVar having the value 10. Within functionExample(...), the value of 10 is copied from myVar to the formal parameter inputVar, so the value of nextVar is 10x2, or 20. The next statement changes the contents of inputVar to 4, so the cout statement within this function produces the output:
Notice what happens when functionExample(...) ends and execution returns to callingFunction(). The contents of myVar is still the same, as the location for myVar differs from where inputVar is stored. Thus, myVar still has the value 10, and the cout statement after the function call will produce the output:
We have seen examples of C++ functions that return no value or a single value. How about when we want the function to return more than one value? We need another function calling mechanism called pass by reference. When using this mechanism, the actual location in memory referenced by the arguments are sent rather than the values in that location. To let the compiler know that you intend to use pass by reference, you attach an “&” to the end of the type name in the formal parameter list in the function declaration and header. When you do this, any changes to the values of the parameters will change the value of the arguments as well.
An example of a function where this is useful is a function that takes two values as input and swaps their order. Consider the following program fragment of a function called swap_values(...) that swaps its two inputs and the main() function that calls swap_values(...).
For this program Swap Inputs to reverse the order of the integers the users types in, the function swap_values(...) must be able to change the values of the arguments. Try removing one or both of the “&” ‘s in this code to see what happens.