|
|
|
|
|
|
|
With simple data typesint, char, float, and so ona value parameter is the default (assumed) kind of parameter. In other words, if you don't do anything special (add an ampersand), a parameter is assumed to be a value parameter. To specify a reference parameter, you have to go out of your way to do something extra (attach an ampersand). |
|
|
|
 |
|
 |
|
|
Value Parameter A formal parameter that receives a copy of the contents of the corresponding actual parameter. |
|
|
|
 |
|
 |
|
|
Reference Parameter A formal parameter that receives the location (memory address) of the caller's actual parameter. |
|
|
|
|
|
|
|
|
Let's look at both kinds of parameters, starting with value parameters. |
|
|
|
|
|
|
|
|
In the NewWelcome program, the PrintLines function heading is |
|
|
|
|
|
|
|
|
void PrintLines( int numLines ) |
|
|
|
|
|
|
|
|
The formal parameter numLines is a value parameter because its data type name doesn't end in &. If the function is called using an actual parameter lineCount |
|
|
|
|
|
|
|
|
then the formal parameter numLines receives a copy of the value of lineCount. At this moment, there are two copies of the dataone in the actual parameter lineCount and one in the formal parameter numLines. If a statement inside the PrintLines function were to change the value of numLines, this change would not affect the actual parameter lineCount (remember, there are two copies of the data). Using value parameters thus helps us avoid unintentional changes to actual parameters. |
|
|
|
|
|
|
|
|
Because value parameters are passed copies of their actual parameters, anything that has a value may be passed to a value parameter. This includes constants, variables, and even arbitrarily complicated expressions. (The expression is simply evaluated and a copy of the result is sent to the corresponding value parameter.) For the PrintLines function, the following function calls are all valid: |
|
|
|
|
|