Loading lessons...
Pass by Reference
Pass by Reference
Earlier, pass-by-value made a copy of the argument. Pass by reference does something more: the function gets direct access to the caller's variable, so it can change it.
Using the ampersand
Add & to the parameter's type:
void swapNums(int &x, int &y) {
int z = x;
x = y;
y = z;
}
int &reads as "reference to an int".- The parameter is not a copy; it refers to the caller's variable.
- The function writes through it.
The difference becomes visible
int main() {
int first = 10;
int second = 20;
swapNums(first, second); // the swap works
cout << first << " " << second; // prints 20 10
return 0;
}
With pass-by-value, a swap like this would have nothing to show. With a reference, the caller's variables are actually reordered.
The call syntax is unchanged
At the call site you just pass the variable - nothing special to write. The & appears only in the definition.
Efficiency: avoiding copies
Even when you don't need to change anything, references are great for efficiency: no copy is made. A big struct or object can be passed by reference instead of duplicated. A common pattern is passing by const reference so the function reads the original without making (or mutating) a copy.
TL;DR
- Reference parameters are marked with
&:void f(int &x). - The function works on the actual caller's variable, not a copy.
- Changes inside the function are visible in the caller.
- The call syntax is the same; only the parameter declares
&. - References avoid copying large values.