In: Computer Science
R5.18The following function swaps two integers, without requiring a temporary variable(C++):
void tricky_swap(int& a, int& b)
{
a = a - b;
b = a + b;
a = b - a;
}
However, it fails in one important case, namely when calling tricky_swap(x, x). Explain what should happen and what actually happens.
What is assumed to happen:
tricky_swap(x,x)
a = a-b;
a = x - x -> a =0
b = a + b;
b = 0 + x -> b = x
a = b - a;
a = x - 0 -> a = x
So at the end value is supposed to be succesfully swapped.
But this not happens because:
a and b refer to only one variable x that is stored at one place in memory. And hence if any of them is changed, value refer by other reference variable automatically gets changed, since it is also referring the same variable x.
thus what actually happens is :
tricky_swap(x,x)
a = a-b;
a = x - x -> a =0 this makes b =0 as well due to reason explained above
b = a + b;
b = 0 + 0 -> b = 0 this makes a =0 as well due to reason explained above
a = b - a;
a = 0 - 0 -> a=0 this makes b =0 as well due to reason explained above
hence at the end, x value is 0.