int n = 5; // this declares a variable, n int & r = n; // this declares r as a reference to n
In the above example, r is now a reference to n. Another way of thinking about it is to think of r as a nickname, or alias, for n. Both variable names now refer to the same storage cell in memory. To declare a reference variable, add the & operator after the type. Here is a small example program that uses a reference variable and illustrates what it is: r.cpp
Note: The notation can become confusing when different sources place the & differently. The following three declarations are equivalent:
int &r = n; int& r = n; int & r = n;
The spacing between the "int" and the "r" is irrelevant. All three of these declare r as a reference variable that refers to n.
Look at this example program: byval.cpp.
This has a function called Twice, which should take in two integer parameters
and double them. Notice that the original variables from the main
program are not affected by this function. The parameters
constitute a one way flow of information -- the function cannot change
the original x and y!
Now look at this example:
byref.cpp.
Run it with the same input values. Notice that the Twice function
does
change the original variables that were passed in! Why? The
parameters were only references to the original data locations, not copies!
The first example of parameter passing is usually called Pass By Value. The second is an example of Pass By Reference.
Pass By Value -- The local parameters are copies of the original
arguments passed in. Changes made in the function cannot affect
the original arguments.
Pass By Reference -- The local parameters are references, or
nicknames, for the original argument variables passed in. Changes
made in the function will affect the originals.
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.
Example:
int Sum(int x, int y);
// return value is passed by value
int& Sum(int x, int y);
// return value is passed by reference
Why?
What if we want a function that does not have to go through the overhead of copying a parameter (perhaps a very large object being passed in), but we also don't want the original to be changed? Then we can protect the original by declaring the parameter as a const.
How?
The format: const typeName & v
This establishes v as a reference to an object that cannot be changed
through the use of the variable v.
Example:
int Function2(const double & r);
Here, r cannot be changed in the function body, but no copies are made
-- we're looking at the original.