Hacker News new | ask | show | jobs
by gobdovan 61 days ago
The XOR trick is only cool in its undefined-behavior form:

a^=b^=a^=b;

Which allegedly saves you 0.5 seconds of typing in competitive programming competitions from 20 years ago and is known to work reliably (on MinGW under Windows XP).

Bonus authenticity: use `a^=a` to zero a register in a single x86 instruction (and makes a real difference for compiler toolchains 30+ years old).

For real now, a very useful application of XOR is its relation to the Nim game [0], which comes in very handy if you need to save your village from an ancient disgruntled Chinese emperor.

[0] https://en.wikipedia.org/wiki/Nim

3 comments

`xor eax, eax` is less code when assembled. That's why compilers generate it.
..and reliably generate it for decades, but you can still manually do it in C for bonus stylistic points!
>Bonus authenticity: use `a^=a` to zero a register in a single x86 instruction (and makes a real difference for compiler toolchains 30+ years old).

Modern compilers will still use xor for zeroing registers on their own.

For instance: https://godbolt.org/z/n5n35xjqx

Variable a(register esi) is first initialized to 42 with mov and then cleared to zero using xor.

Yes, the whole comment is tongue in cheek for pointless manual optimizations.
> The XOR trick is only cool in its undefined-behavior form:

> a^=b^=a^=b;

I believe this is defined in C++ since C++17, but still undefined in C.