Reference parameters |
Java and C++ both use call by value in passing parameters. That is if we have
void m(int p) { ... } ... q = 23; m(q);
then when m(q) is called, the value of q - i.e., 23 - is copied into the memory slot associated with p in m's activation record. Because p and q refer to different locations in memory, changing p has no impact on q.
As a result, the call swap(a,b) of the following function has no impact:
void swap(int m, int n) { int temp = m; m = n; n = temp; }
That is, while the values of the parameter m and n are swapped, after the function returns the values of a and b are the same as they were before.
To make this possible, C++ introduced reference parameters:
void swap(int &m, int &n) { int temp = m; m = n; n = temp; }
Now when swap(a,b) is called, the locations of a and b are passed rather than their values. Thus m is identified with the location of a and n is associated with the location of b. Thus any change to m is really a change to a and any change to n is also a change to b as they are just different names for the same variable. Hence swap does what it is supposed to.
Because reference parameters are associated with the locations of the actual parameters, the actual parameters must be variables and not general expressions. Thus swap(17, 2+3) is illegal.
Reference parameters |