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:
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.
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.
void swap (int& x, int& y) {
int temp = x;
x = y;
y = temp;
}
void add (int& z, int q) {
z = z + y;
}
int multiply(int a, int b) {
int total = a * b;
return total;
}
Create a function called addNum that takes two parameters, an integer x and an integer y. The function should add y to x, then print x. The variable x should be modified, while the variable y should not.