logoalt Hacker News

gobdovantoday at 6:53 AM3 repliesview on HN

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


Replies

MathMonkeyMantoday at 8:05 AM

`xor eax, eax` is less code when assembled. That's why compilers generate it.

show 2 replies
leni536today at 9:31 AM

> 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.

ginkotoday at 8:14 AM

>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.

show 1 reply