temp = x;
x = y;
y = temp;
Tom showed me a different way. A tricky way. A way that only really works with integer values.
y = y ^ x;
x = y ^ x;
y = y ^ x;
The caret ( ^ ) is the symbol for an Exclusive Or for those of you not current in C#.
It’s Truth table looks something like the image on the right. Of course when Tom showed me this I had to try it out. I used the values X = 10 and Y = 3. In Binary the results looked something like this:
Naturally I had to write a program to double check my math.
This is all fun and interesting in a geeky sort of way. But is it a good idea? No so much. For one thing it is tricky, unusual and can easily confuse people. For another there is no speed gain. In fact the XOR operation is actually slower than the copy to another location operation. Not by a lot. They can both be register operations which are the fastest sort of CPU operations. But without a good performance gain there is no real reason to use the XOR method (even if it being confusing were not enough reason) over the swap operation. Lastly the fact that this is not as general purpose as the swap method is the nail in the coffin as far as I’m concerned.
But it sure is cool. In a geeky sort of way.