3 ms·
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
by gobdovan 6mo 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 https://en.wikipedia.org/wiki/Nim
- MathMonkeyMan 6mo ago`xor eax, eax` is less code when assembled. That's why compilers generate it.
- gobdovan 6mo ago..and reliably generate it for decades, but you can still manually do it in C for bonus stylistic points!
- deleted 6mo ago[deleted]
- ginko 6mo ago>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 https://godbolt.org/z/n5n35xjqx Variable a(register esi) is first initialized to 42 with mov and then cleared to zero using xor.
- gobdovan 6mo agoYes, the whole comment is tongue in cheek for pointless manual optimizations.
- leni536 6mo ago> 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.