A deep dive into the XOR swap trick, covering what XOR is, how the trick works, and whether it's actually useful. Compiler analysis shows that for local variables, modern compilers (e.g., clang -O2) optimize both XOR-swap and temp-variable swap into identical assembly. For pointer-based swaps, the XOR version generates more instructions and is strictly worse, partly because pointer aliasing prevents the compiler from optimizing it away. Adding the C `restrict` keyword lets the compiler eliminate the XOR entirely. The addition-based swap alternative is explored, including its undefined behavior risks and floating-point precision failures. The post concludes that the XOR swap trick is largely a historical curiosity — potentially useful in register-starved assembly contexts like MIPS, but never necessary on x86 (which has had XCHG since 1978). Other XOR tricks, like finding the unique element in a list of pairs, are briefly mentioned.
Table of contents
Too much Discussion of the XOR swap trickWhat does XOR mean?What is a logical XOR?What is the XOR bitwise operator?What is the XOR swap trick?Usage 1: Swapping local variablesUsage 2: Swapping through pointersWhy didn’t the compiler optimise the XOR swap away?What about the addition swap trick?So, why do people care about the XOR swap trick?Are there other XOR tricks?Sort: