4.2 Pass-by-reference, C++

In C++, you can pass a argument by reference. Here is an example:

void inc(int &x)
{
  x = x + 1;
}

Note that the & symbol does not mean address-of. It means that ``x is a reference to an integer''. Consequently, when we see x in subroutine inc, it means ``whatever x is referring to.''

x does not have an integer value, it refers to one.

In the expression x = x + 1;, the right hand side says: ``evaluate the sum of 1 and the value referred to by x.'' The left hand side says ``store the value to whatever storage referred by x.''

Now consider the following invocation:

// before
inc(z);
// after

The value of z (of the caller) will increment in this case. This is because the subroutine inc is not given the value (or a snapshot there of) of argument z, it is given the method to find variable z. As a result, whatever we do to parameter x is done to argument z.

It only makes sense the the argument used to specify parameter x must be the storage of an integer. This means that the following invocation will result in a compiler error:

inc(z+1);

This results in an error because the expression z+1 only specifies a value, but not a place to store an integer.

Copyright © 2006-08-28 by Tak Auyeung