Reputation: 595
I read that three variables a,b, and c can be swapped using the single statement below: c = a ^ b ^ c ^ (a=b) ^ (b=c)
Similarly, two variables a and b can be swapped as: a = a ^ b ^ (b=a)
Can somebody please explain how does this work?
P.S. Here is the link saying so. http://p--np.blogspot.ro/2011/04/reverse-linked-list-using-only-2.html
Upvotes: 3
Views: 431
Reputation: 178461
You only need to make in the original statement all assignments (except the one you want to change to) are countered:
a = a ^ b ^ c ^ (b=c) ^ (c=a);
You assign c=a
, b=c
. The return value of those is a
and c
respectevely, so, you want to "counter" a
and c
, and you use the fact that a^a == 0
and c^c == 0
, and just add a,c at the beginning.
In addition, you add a b
, to assign a
to the value of b
.
Note that as discussed in comments, it is language dependent if the above is guaranteed to succeed or not. In Java, for example - it is: The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.
, while in others, such as C, it is not.
Upvotes: 1