< Previous | Contents | Next >

Passing by Reference

Its possible to give a function access to an argument variable by passing a parameter a reference to the argument variable. As a result, anything done to the parameter will be done to the argument variable. To pass by reference, you must first declare the parameter as a reference.

You can tell that a call to goodSwap() passes both arguments by reference by looking at the function header.

void goodSwap(int& x, int& y)

This means that when I call goodSwap() with the following line, the parameter x

will refer to myScore and the parameter y will refer to yourScore.

goodSwap(myScore, yourScore);

This means that x is just another name for myScore and y is just another name for yourScore. When goodSwap() executes and x and y exchange values, what really happens is that myScore and yourScore exchange values.

After the function ends, control returns to main(), where I send myScore and yourScore to cout. This time 1000 and 150 are displayed. The variables have exchanged values. Ive taken the large score and left you with the small one. Success at last!

Passing References for Efficiency 195