Next: Summary
Up: Introduction to User-defined functions
Previous: Example Function: Raising to
Suppose the function power
above is now amended to include the
statement
n++;
just before the final closing }
and the following statements are executed:p = 4; y = power(x, p); cout << p;
What would be printed out for the value of p
? In fact instead
of the value 5 that you might expect p
would still have the
value 4. This is because the parameter has been passed by
value. This means that when the function is called a copy of
the value of the actual parameter used in the call is passed across
to the memory space of the function. Anything that happens inside the
function to this copy of the value of the parameter cannot affect the
original actual parameter. All the examples that have been considered
have used call-by-value parameters. This is because all the parameters
used have been input parameters. To make a parameter call-by-value it
is specified in the parameter list by giving its type followed by its
name.
Thus if a parameter is only to be used for passing information into a function and does not have to be returned or passed back from the function then the formal parameter representing that parameter should be call-by-value. Note also that since the function cannot change the value of a call-by-value parameter in the calling program strange side effects of calling a function are avoided.