13.9) Use of Reference Parameters
In the original version of swap.cpp, function parameters x
and y
are copies of the variables first
and second
that were used as arguments in the function call; they do not represent the variables themselves. This is known as call-by-value behaviour.
What happens when we change the function definition to this?
void swap(int& x, int& y) { ... }
x
and y
are now references to the original variables that were used as arguments - so any changes made to x
and y
are in fact changing first
and second
, giving us precisely the outcome we desire. This is known as call-by-reference behaviour.