|
|
|
|
|
|
|
PrintLines(3);
PrintLines(lineCount);
PrintLines(2 * abs(10 - someInt)); |
|
|
|
|
|
|
|
|
There must be the same number of actual parameters in a function call as there are formal parameters in the function heading.* Also, each actual parameter should have the same data type as the formal parameter in the same position. Notice how each formal parameter in the following example is matched to the actual parameter in the same position (the data type of each actual parameter is what you would assume from its name): |
|
|
|
|
|
|
|
|
If the matched parameters are not of the same data type, implicit type coercion takes place. For example, if a formal parameter is of type int, an actual parameter that is a float expression is coerced to an int value before it is passed to the function. As usual in C++, you can avoid unintended type coercion by using an explicit type cast or, better yet, by not mixing data types at all. |
|
|
|
|
|
|
|
|
As we have stressed, a value parameter receives a copy of the actual parameter and therefore the actual parameter cannot be directly accessed or changed. When a function returns, the contents of any value parameters are destroyed, along with the contents of the local variables. The difference between value parameters and local variables is that the values of local variables are undefined when a function starts to execute, whereas value parameters are automatically initialized to the values of the corresponding actual parameters. |
|
|
|
|
|
|
|
|
Because the contents of value parameters are destroyed when the function returns, they cannot be used to return information to the calling code. What if we do want to return information by modifying the actual parameters? We must use the second kind of parameter available in C++: reference parameters. Let's look at these now. |
|
|
|
|
|
|
|
|
A reference parameter is one that you declare by attaching an ampersand to the name of its data type. It is called a reference parameter because the called function can refer to the corresponding actual parameter directly. Specifically, the function is allowed to inspect and modify the caller's actual parameter. |
|
|
|
 |
|
 |
|
|
*This statement is not the whole truth. C++ has a special language featuredefault parametersthat lets you call a function with fewer actual parameters than formal parameters. We do not cover default parameters in this book. |
|
|
|
|
|