- In this version of the
example, the Twice function looks like this:
void Twice(int& a, int& b)
{
a *= 2;
b *= 2;
}
- Note that when it is run, the variables passed into Twice
from the main() function DO get changed by the
function
- The parameters a and b are still local to the
function, but they are reference variables (i.e. nicknames to
the original variables passed in (x and y))
- When reference variables are used as formal parameters, this is known
as Pass By Reference
void Func2(int& x, double& y)
{
x = 12; // these WILL affect the original arguments
y = 20.5;
}
- When a function expects strict reference types in the parameter list,
an L-value (i.e. a variable, or storage location) must be passed in
int num;
double avg;
Func2(num, avg); // legal
Func2(4, 10.6); // NOT legal
Func2(num + 6, avg - 10.6); // NOT legal
- Note: This also works the same for return types. A return by value
means a copy will be made. A reference return type sends back a reference
to the original.
int Task1(int x, double y); // uses return by value
int& Task2(int x, double y); // uses return by reference
This is a trickier situation than reference parameters (which we will not
see in detail right now).