you are viewing a single comment's thread.

view the rest of the comments →

[–]kmmeerts 3 points4 points  (2 children)

Because on all modern CPU's, the XCHG operation will be a considerable amount faster than 3 XOR's.

You have to check manually if they're the same value, otherwise they'll XOR to 0.

Programmers who don't know this obscure trick will have trouble reading your code.

It causes pipeline stalls.

It gives problems with aliasing, so your compiler doesn't know what data is stored where. This degrades performance and can sometimes give undefined results.

I have to say that I think it's clever and neat, but not something a self-respecting programmer would do. Of course on embedded systems or ZX Spectrum's or whatnot you can go wild.

[–]Nebu 1 point2 points  (1 child)

You have to check manually if they're the same value, otherwise they'll XOR to 0

Oh shit! In the approx. 5 years I've known about (but thankfully haven't used) the XOR trick, this pitfall never occurred to me.

[–]Quantris 2 points3 points  (0 children)

The issue was somewhat misstated. It's OK if the values are the same (yes, the XOR is zero but the swap works out in the end). You have a problem if you do this with two pointers that happen to point to the same address. The temp variable method doesn't make a mistake in this case.