C++ Notes: Reference Parameters

Value Parameters

If nothing special is written, argument values are copied into corresponding formal parameters, which are like local variables. Assignment to formal parameters or local variables does not change the arguments.

Reference Parameters allow assignment

Reference parameters are used to solve the problem of changing the arguments.

Mark reference parameters with a &

To indicate a reference parameter, an ampersand (&) is written in the function prototype and header after the parameter type name.

Example - Swap (bad solution)

Let's say you want to exchange the values in two arguments.
int a = 5;
int b = 10;

swap(a,b);

// We want a=10 and b=5, how do we write it?
Here's an example that does NOT work correctly, altho there is no error message.
void swap(int x, int y) {  // BAD BAD BAD BAD BAD BAD BAD
  int temp;
  temp = x;
  x = y;
  y = temp;
}
Because x and y are like local variables, they have no effect on the arguments a and b.

Example - Swap (good solution)

If the parameters are marked as reference parameters, the memory address of each argument is passed to the function. The function can use this address to either get the value or set the value. Here is swap written correctly. The only change is the addition of the & to the parameter types.
void swap(int& x, int& y) {
  int temp;
  temp = x;
  x = y;
  y = temp;
}

L-values required for actual reference parameters

An l-value is something that you can assign to. This name is short for left-value, referring to the kind of value that must be on the left side of an assignment statement.