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