
Reference Parameters
#include <iostream>
using namespace std;
// Swap two values.
void swap(double &a, double &b)
{
double tmp = a;
a = b;
b = tmp;
}
// Return multiple results.
void stats(double x, double y, double &absdif, double &mean, double &sumsqr)
{
if(x > y) swap(x, y);
absdif = y - x;
mean = (x + y) / 2.0;
sumsqr = x*x + y*y;
}
int main()
{
double a = 10.45;
double b = 20.22;
cout << a << " " << b << endl;
swap(a, b);
cout << a << " " << b << "\n" << endl;
double c = 4.56;
double d = -3.45;
double absdif, mean, ss;
stats(c, d, absdif, mean, ss);
cout << c << " " << d << " " << absdif << " " <<
mean << " " << ss << endl;
stats(22.0, 41.5, absdif, mean, ss);
cout << absdif << " " << mean << " " << ss << endl;
}
The usual way of passing parameters in C++, and the only way in C, is
by value. Each parameter becomes a copy of its argument, and changes to
in the function body do not make changes in the caller. This is similar
to Java. C++ provides
reference parameters, which are denoted using an & in front of
the parameter name. Reference parameters
become aliases for their arguments, and changes to the parameters
immediately change the arguments. You cannot send an expression
argument to a reference parameter; you must send something which
could appear on the left side of an assignment.
The swap function is a classic use of reference parameters.
When the reference parameters are exchanged, the arguments are
exchanged since the parameters are aliases for them.
Also notice that the stats function receives x and y by
value, and uses swap to exchange its copies, but this does not
effect the values of c and d in the main.
Reference parameters are by far the main use of the reference
mechanism in C++. It can also be used for return values, and,
though it seems to have no practical use, ordinary variables.
Reading: pp. 125-144 exc. arrays