< previous page page_350 next page >

Page 350
DoThis(someFloat, someInt);
DoThis(9.83, intCounter);
DoThis(4.9 * sqrt(y), myInt);
In the DoThis function, the first parameter is a value parameter, so any expression is allowed as the actual parameter. The second parameter is a reference parameter, so the actual parameter must be a variable name. The statement
DoThis(y, 3);
generates a compile-time error because the second parameter isn't a variable name. Earlier we said the syntax template for an actual parameter list is
0350-01.gif
But you must keep in mind that Expression is restricted to a variable name if the formal parameter is a reference parameter.
There is another important difference between value and reference parameters when it comes to matching actual parameters with formal parameters. With value parameters, we said that implicit type coercion occurs if the matched parameters have different data types (the value of the actual parameter is coerced to the data type of the formal parameter). With reference parameters, if the matched parameters have different data types, a curious thing happens. C++ copies the value of the actual parameter into a temporary variable of the correct type and passes the address of the temporary variable to the formal parameter. When the function returns, the temporary variable is discarded. Any changes that you expected the function to make to your actual parameter were not made at all. To avoid this unpleasant result, always verify that the actual parameter has exactly the same data type as the formal parameter.
The following table summarizes the appropriate forms of actual parameters.
Formal ParameterActual Parameter
Value
A variable, constant, or arbitrary expression (type coercion
may take place)
Reference
A variable only, of exactly the same data type as the formal
parameter

 
< previous page page_350 next page >