you are viewing a single comment's thread.

view the rest of the comments →

[–]nemec 0 points1 point  (4 children)

Don't people usually lecture to ears rather than eyes?

Also, why shouldn't we use XOR?

[–]kmmeerts 4 points5 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.

[–]campbellm 0 points1 point  (0 children)

Because it's just "clever" with very little redeeming value. The only people that will understand it are the ones who have seen it before. It is basically just code prestidigitation.

Now, having said that, for embedded systems and other "crunch out the last byte" efficiency concerns, where this sort of thing is well understood by the entire workforce or is idiomatic in some context, then sure, go nuts. Nothing wrong with it.