The C++Course provides a general introduction to programming in C++. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.

Passing Other Types by Reference

It's not just structures that can be passed by reference. All the other types we've seen can, too. For example, to swap two integers, we could write something like:

void swap (int& x, int& y)
  int temp = x;
  x = y;
  y = temp;

We would call this function in the usual way:

  int i = 7;
  int j = 9;
  swap (i, j);
  cout << i << j << endl;

The output of this program is 97. Draw a stack diagram for this program to convince yourself this is true. If the parameters x and y were declared as regular parameters (without the &s), swap would not work. It would modify x and y and have no effect on i and j.

When people start passing things like integers by reference, they often try to use an expression as a reference argument. For example:

  int i = 7;
  int j = 9;
  swap (i, j+1);         // WRONG!!

This is not legal because the expression j+1 is not a variable---it does not occupy a location that the reference can refer to. It is a little tricky to figure out exactly what kinds of expressions can be passed by reference. For now a good rule of thumb is that reference arguments have to be variables.

Last Update: 2005-12-05