Sunday, February 11, 2007

swap using XOR

In one of my previous posts I described a few ways of swapping two numbers using xor operation in a sinlge line. The discussion is not correct or rather incomplete in the sense that the algorithm needs to be guarded by an if condition. The algorithm that exercises proper care of sequence points is as below:

swap (int &a, int &b) {
if (&a != &b) {
a ^= b;
b ^= a;
a ^= b;
} }

It is crutial that the two number must not be located at the same address. The two numbers must have different identities. The algorithm works even though the values are the same.

No comments: