AI Briefing
KO

Too Much Discussion About the XOR Swap Trick

·2026.04.13 20:22

Key point

The XOR swap trick offers no real benefit for local variables, pointers, or registers.

Details

XOR is an operation that returns 1 when two values differ and 0 when they are the same, and using this, you can swap two values without a temporary variable.

  • The XOR swap in the form a ^= b; b ^= a; a ^= b; works mathematically.
  • However, for local variables, the compiler already recognizes the swap intent and optimizes it into simpler code.
  • Under clang -O2, XOR swap and temp variable swap actually end up as the same assembly.

It becomes clearer with swaps via pointers.

  • swap_temp(&x, &x) preserves the result even when writing to the same address twice,
  • but swap_xor(&x, &x) destroys the value to 0 at the first XOR.
  • So the two functions are not semantically equivalent, and the compiler has no choice but to emit the XOR operation as-is.
  • If restrict is added to guarantee no aliasing, the compiler removes the XOR again and turns it into the same form as the temp swap.

Addition/subtraction swap is also introduced, but it's even more problematic.

  • For integers, there is a risk of signed overflow UB.
  • For floating point, precision loss can cause values to silently disappear.
  • So while the XOR version at least avoids overflow UB, it still has no practical use.

The reason this technique gets mentioned is mostly because it's an interview trick.

  • The case where it actually matters is roughly limited to low-level assembly with registers full.
  • However, in most modern environments, three movs or a dedicated swap instruction is better.
  • x86 has long provided XCHG, and there are architectures like the Z80 where XOR swap can't easily be generalized.

Finally, another use of XOR is noted.

  • When one value appears only once in a list while all others appear twice, XORing the whole list leaves the unique value.
  • This is a representative application using XOR's property of canceling out duplicate values.

The conclusion is clear. XOR swap is unnecessary in most C code, often worse, and sometimes dangerous.

This summary was generated automatically by AI. Check the original for the author's claims and context. Copyright belongs to the original author.

Our guide explains how the AI works. Report summary errors, attribution issues, or removal requests via Contact.