You need to pass the variables by reference:
void swap_values( int& x, int& y )
{
int z;
z = y;
y = x;
x = z;
}
pass-by-value
and pass-by-reference
are key concepts in major programming languages. In C++, unless you specify by-reference, a pass-by-value
occurs.
It basically means that it's not the original variables that are passed to the function, but copies.
That's why, outside the function, the variables remained the same - because inside the functions, only the copies were modified.
If you pass by reference (int& x, int& y
), the function operates on the original variables.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…