Subtleties Of Programming
Be careful in swapping with XOR
While coding for the problem-2.3-7, some how I was not in my default mode of not thinking while coding. To test my programs I was writing a random array generator. One part of it was to swap two array entries. Now, the most straight forward way to swap two array elements is
int tmp = arr[i];arr[i] = arr[r];arr[r] = tmp;
But, knowing the xor method, I thought why not save a variable.
b are to be swapped, then the code suffices.
a ^= b;b ^= a;a ^= b;
So now the question is, would this work on an array. Ex.
arr[i] ^= arr[r];arr[r] ^= arr[i];arr[i] ^= arr[r];
Here's a subtle bug. If
r are same, then it won't. The reason being
that we loose the original value. If both indexes are same, the same array entry
would be xor'ed with itself. Wiki
page explains it better, and
why it should be avoided. Again, I learn the evils of
premature optimization. Subtleties of programming!