Skip to interview prep
Apexed

411. What are the pitfalls of swapping two variables with XOR (x ^= y; y ^= x; x ^= y)?

MediumAlgorithm analysis

Technical
Show model answer

If both names refer to the same memory location (for example `a[i]` and `a[j]` with i = j), the first step sets it to zero and the value is lost. Guard with an equality check of the locations or just use a temporary. The add/subtract version (`x = x + y; y = x − y; x = x − y`) has the same aliasing issue and can overflow in fixed-width types.

It is also not faster on modern hardware: the three operations depend on each other, so they cannot run in parallel, whereas a temporary-variable swap is often eliminated by register renaming or compiled to a single exchange. It only works for integers, hurts readability, and in JavaScript or Python the idiomatic swap is destructuring: `[a, b] = [b, a]` or `a, b = b, a`.

What are the pitfalls of swapping two variables with XOR (x ^= y; y ^= x; x ^= y) — Data structures & algorithms interview question — Apexed