Pass By Reference (or how do I change the values
of those parameters?)
Recall - formal parameter list definition we looked at when introducing
functions:
Datatype VariableName, Datatype VariableName, ...
Recall - VariableName was optional in the function prototype
- VariableName was required
in the function defiinition
EX: void fnct1 (int, int);
void fnct1 (int x, int y);
// are both examples of valid function prototypes
EX: // actual function header in function
definition must include VariableName
void fnct1 (int x, int y)
{
statement;
.
.
.
}
The above formal parameter list is not quite a complete definition
, let's now redefine it:
Datatype& VariableName, Datatype
& VariableName,...
Note the addition on the &(ampersand) following the Datatype
The & is optional. When omitted - the parameters are accepted
as Pass By Value
When the & is included - the parameters are accepted as Pass By Reference.
Pass By Reference
If we wish for the called function to be able to refer to the corresponding
actual parameters directly we include the ampersand (&) directly following
the Datatype in the formal parameter list.
- the function is allowed to inspect and modify the callers actual parameters
When a function is invoked using a reference parameter:
- the location (memory address) of the actual parameter , not its value,
is passed to the function
- there is only one copy of the info and it is used by both the caller
and the called function
- the actual parameter and formal parameter become synonyms for the same
location in memory
Be careful using formal reference parameters -- any change made to it affects
the actual parameter in
its calling code. i.e. the value of the actual parameter is changed.
EX of syntax:
void functionX (int&, float, char&
); // function prototype with 3 parameters,
the 1st and 3rd are by reference (changable)
// and the second parameter - a float is by value - not changable
void main ();
{
int x;
float y = 3.5;
char ch;
functionX(x, y, ch);
// I anticipate that x and ch may be modified while
in functionX. (reference parameters- w/ & in header)
// I also
anticiapte that y (being passed by value) cannot be modified (value parameter
- no & in header)
}
void functionX(int& a, float b, char&
c)
{
statement;
.
.
.
}
When the formal parameter is:
- Value
- actual parameter may be:
- variable
- constant
- expression
- Reference
- actual parameter must be: