- The classic swap algorithm using a temporary variable — and why it's usually the best choice
- How to swap two integers using only addition and subtraction
- How to swap two integers using the bitwise XOR operator
- Why the XOR method works (XOR is its own inverse)
- The overflow and zero-input caveats of both tricks
- Why the temporary variable is still preferred in production code
Why swap without a third variable?
Swapping two variables is one of the oldest exercises in programming. The standard way uses a temporary:
int temp = a;
a = b;
b = temp;
This is correct, clear, and works for any type. It's what you should use in real code, unless you have a specific reason not to. But "swap without a temporary" is a classic puzzle — and the puzzle is a good way to learn several deep ideas: how arithmetic can encode two values in one, how XOR works as a reversible operation, and how seemingly clever tricks have hidden pitfalls.
The motivation for the trick is memory savings — one fewer variable, one fewer 4 bytes. On modern hardware, this saving is negligible. A 4-byte temporary is nothing next to the megabytes of cache and gigabytes of RAM available. So the trick is rarely a real optimization. It's an intellectual exercise, a viva question, and a nice way to demonstrate some properties of arithmetic and bitwise operators.
Two techniques are common. The arithmetic method uses addition and subtraction: the sum of the two values encodes both, and subtracting the known original recovers the other. The XOR method uses the XOR operator, which has the property that x ^ x = 0 and x ^ 0 = x — so applying XOR twice with the same value undoes the operation, allowing you to recover the original values without any arithmetic overflow.
💡 In one line: you can swap two integers without a temporary by encoding both values in one variable (arithmetic or XOR), then decoding them back to their original forms in the opposite order. The trick is clever; the temp variable is still the better choice in real code.
Two techniques: arithmetic and XOR
Both techniques work by storing enough information in a to recover both original values, then using that information to reconstruct them. Here's how each one works.
1. The arithmetic method
Start with a = 5, b = 10.
a = a + b;→abecomes 15 (the sum of both originals),bstays 10.b = a - b;→bbecomes 15 − 10 = 5 (the originala),astays 15.a = a - b;→abecomes 15 − 5 = 10 (the originalb),bstays 5.
After three operations, a = 10, b = 5 — swapped. The sum 15 was the intermediate state that carried enough information to recover both originals. Once b was reconstructed to 5, a could be reconstructed to 10 using the same sum.
The catch: a + b can overflow if both operands are near INT_MAX. If a = 2,000,000,000 and b = 2,000,000,000, the sum 4,000,000,000 exceeds INT_MAX (2,147,483,647), and the result wraps around to a negative number. Subsequent subtractions then produce incorrect values. This is undefined behavior in the C standard — technically the compiler can do anything. In practice, on two's-complement systems, the wrap-around happens consistently, and the swap still works. But it's not portable, and it's a real bug source if you ever move to a platform with different overflow behavior.
2. The XOR method
Start with a = 5 (binary 0101), b = 10 (binary 1010).
a = a ^ b;→abecomes0101 ^ 1010 = 1111= 15,bstays 10.b = a ^ b;→bbecomes1111 ^ 1010 = 0101= 5 (the originala),astays 15.a = a ^ b;→abecomes1111 ^ 0101 = 1010= 10 (the originalb),bstays 5.
The key property: x ^ x = 0 and x ^ 0 = x. So when b XORs with the encoded value a, the original b bits cancel out (since they appear in both), leaving the original a bits. Then when a XORs with the now-restored b, the original a bits cancel out, leaving the original b. XOR is its own inverse — applying the same operation twice reverses it.
The XOR method avoids overflow entirely, because XOR is a bit-level operation with no carries. It works for any pair of integers within the type's range. The catch: if a and b are the same variable (same memory location), the swap fails — the first line sets a = a ^ a = 0, and the subsequent lines leave both at 0. This can happen with array indices or pointers. The arithmetic method has the same problem for the same reason (you can't swap a value with itself and expect the values to change — they're already the same).
| Aspect | Arithmetic | XOR |
|---|---|---|
| Operations | + and − | ^ only |
| Overflow risk | Yes (if a + b overflows) | No |
| Works for floats | Yes | No (XOR is integer-only) |
| Works if a == &b | No (sets both to 0) | No (sets both to 0) |
| Clarity | Moderate | Low (obscure) |
| Best for production | No | No — use a temp |
Both methods are interesting — and worth knowing, for interviews and for understanding the underlying operators. But the temporary-variable swap is the right choice in real code, for three reasons: it works for any type (not just integers), it has no overflow caveats, and it's obvious to any reader.
🎯 Key idea: the no-temp swap is a puzzle, not an optimization. It's fun to learn, useful for interviews, and instructive for understanding XOR and arithmetic. But the temporary-variable version is clearer, safer, and works for more types. Use it in production; enjoy the trick in exercises.
Complete C Programs
Here is the complete program, showing both methods side by side:
Program: swap two integers with arithmetic, then with XOR
#include <stdio.h>
int main(void) {
int a, b;
printf("Enter two integers: ");
scanf("%d %d", &a, &b);
printf("\n--- Arithmetic method ---\n");
printf("Before: a = %d, b = %d\n", a, b);
/*
* Step 1: a = a + b (a holds the sum of both)
* Step 2: b = a - b (b recovers the original a)
* Step 3: a = a - b (a recovers the original b)
*/
a = a + b;
b = a - b;
a = a - b;
printf("After: a = %d, b = %d\n", a, b);
printf("\n--- XOR method ---\n");
printf("Before: a = %d, b = %d\n", a, b);
/*
* Step 1: a = a ^ b (a holds the XOR of both)
* Step 2: b = a ^ b (b recovers the original a)
* Step 3: a = a ^ b (a recovers the original b)
*
* XOR is its own inverse: x ^ x = 0, x ^ 0 = x.
*/
a = a ^ b;
b = a ^ b;
a = a ^ b;
printf("After: a = %d, b = %d\n", a, b);
return 0;
}
The program reads two integers, applies the arithmetic swap, prints the result, then applies the XOR swap (which swaps them back), and prints again. Since the two methods are inverses of themselves — each undoes its own swap — the final values are back to their originals.
And here's a step-by-step trace version, which prints the values of a and b after each line, so you can see the swap happen live:
Variant: trace each step
#include <stdio.h>
int main(void) {
int a = 5, b = 10;
printf("Start: a = %2d, b = %2d\n", a, b);
a = a + b;
printf("a = a + b: a = %2d, b = %2d\n", a, b);
b = a - b;
printf("b = a - b: a = %2d, b = %2d\n", a, b);
a = a - b;
printf("a = a - b: a = %2d, b = %2d\n", a, b);
printf("\nNow swap back with XOR:\n\n");
a = a ^ b;
printf("a = a ^ b: a = %2d, b = %2d\n", a, b);
b = a ^ b;
printf("b = a ^ b: a = %2d, b = %2d\n", a, b);
a = a ^ b;
printf("a = a ^ b: a = %2d, b = %2d\n", a, b);
return 0;
}
This variant is more educational — you see each variable's value change at each step. Start with 5 and 10. After a = a + b, a holds 15 (the sum). After b = a - b, b becomes 15 − 10 = 5 (recovered original a). After a = a - b, a becomes 15 − 5 = 10 (recovered original b). Swapped! Then the XOR block swaps them back, with the same intermediate values but a different mechanism.
Program Output
Here is typical output from the first program:
Enter two integers: 5 10
--- Arithmetic method ---
Before: a = 5, b = 10
After: a = 10, b = 5
--- XOR method ---
Before: a = 10, b = 5
After: a = 5, b = 10
The arithmetic method swapped 5 and 10 into 10 and 5. The XOR method then swapped them back into 5 and 10. Both methods did their job correctly — the arithmetic one for the swap, the XOR one for undoing it.
And here is the trace version:
Start: a = 5, b = 10
a = a + b: a = 15, b = 10
b = a - b: a = 15, b = 5
a = a - b: a = 10, b = 5
Now swap back with XOR:
a = a ^ b: a = 15, b = 5
b = a ^ b: a = 15, b = 10
a = a ^ b: a = 5, b = 10
The arithmetic trace is clear: 5, 10 → 15, 10 → 15, 5 → 10, 5. The XOR trace is the same pattern of intermediate values — 15 in a is the "combined" state, then it decomposes back. For this input, arithmetic and XOR produce the same intermediates because 5 + 10 = 5 ^ 10 = 15 (a coincidence of these particular bits). Try other inputs — like 3 and 7, or 12 and 5 — and the intermediates diverge, but the final swapped results always match.
With negative numbers:
Enter two integers: -5 10
--- Arithmetic method ---
Before: a = -5, b = 10
After: a = 10, b = -5
--- XOR method ---
Before: a = 10, b = -5
After: a = -5, b = 10
Negative numbers work fine in both methods. The arithmetic one handles them because signed addition and subtraction are well-defined (unless overflow). The XOR one handles them because XOR operates on the bit patterns of the integers, and the two's-complement representation of negatives is well-suited to the trick.
With a potential overflow (both values near INT_MAX):
Enter two integers: 2000000000 2000000000
--- Arithmetic method ---
Before: a = 2000000000, b = 2000000000
After: a = 2000000000, b = 2000000000
--- XOR method ---
Before: a = 2000000000, b = 2000000000
After: a = 2000000000, b = 2000000000
Both values being equal means the swap is a no-op — they both start and end at 2,000,000,000. The arithmetic method would overflow on the first line (a + b = 4,000,000,000, exceeding INT_MAX), but the subsequent subtractions happen to recover correctly on most two's-complement systems. The XOR method has no such concern — 2,000,000,000 ^ 2,000,000,000 = 0, but since both values are the same, the swap still leaves both equal. Try it with 2,000,000,000 and 1,000,000,000 to see the overflow case more clearly.
🔍 Try this: run the program with a = 2000000000 and b = 1000000000. The arithmetic method overflows, but on most systems the swap still works (though it's undefined behavior). The XOR method never overflows. This is the clearest demonstration of why the XOR method is "safer" for arbitrary integers — but also of why you should still just use a temporary variable and avoid the question entirely.
Step-by-Step Explanation
Let's walk through the arithmetic method and the XOR method in detail, then discuss the caveats.
1. The arithmetic method, step by step
Start with a = 5, b = 10.
- Step 1:
a = a + b;—abecomes 5 + 10 = 15.bstays 10. Nowaencodes both original values: it's the sum. The originals are 5 and 10, and the sum is 15. Note that froma = 15alone, you can't recover 5 and 10 — many pairs sum to 15. But you also haveb = 10, so you can recover the 5 by subtracting: 15 − 10 = 5. - Step 2:
b = a - b;—bbecomes 15 − 10 = 5.astays 15. Nowb= 5, the original value ofa. The "original a" has moved tob. - Step 3:
a = a - b;—abecomes 15 − 5 = 10.bstays 5. Nowa= 10, the original value ofb. The "original b" has moved toa. Swap complete.
The elegance is in the intermediate state: a briefly holds the sum of both values. Then each original is recovered by subtracting the other. Since addition is commutative (a + b = b + a), the order doesn't matter — you can do a = a + b; b = a - b; a = a - b; or b = b + a; a = b - a; b = b - a; and both work.
2. The XOR method, step by step
Start with a = 5 (binary 0101), b = 10 (binary 1010).
- Step 1:
a = a ^ b;— bitwise XOR:0101 ^ 1010 = 1111= 15.a= 15,b= 10. Note that this timeadoesn't hold the sum (arithmetic), it holds the XOR (bitwise). The value happens to be 15 here, same as the sum, but for different inputs the values differ. - Step 2:
b = a ^ b;—1111 ^ 1010 = 0101= 5.a= 15,b= 5. The XOR with the originalbbits "cancels out" the originalbcontribution ina, leaving the originala. - Step 3:
a = a ^ b;—1111 ^ 0101 = 1010= 10.a= 10,b= 5. The XOR with the now-restoredbbits cancels out the originalacontribution ina, leaving the originalb. Swap complete.
The key property is that XOR is its own inverse: (x ^ y) ^ y = x. So when you XOR a value with the same thing twice, you get the original. In step 2, a ^ b where a is the XOR of the originals and b is the original b — that leaves the original a. In step 3, a ^ b where a is again the XOR of the originals and b is now the recovered original a — that leaves the original b.
3. Why XOR works: the algebraic property
XOR (exclusive OR) satisfies three useful properties:
- Commutative:
x ^ y = y ^ x - Associative:
(x ^ y) ^ z = x ^ (y ^ z) - Self-inverse:
x ^ x = 0, andx ^ 0 = x
Together, these imply that (x ^ y) ^ y = x ^ (y ^ y) = x ^ 0 = x. Apply that to the swap:
- After step 1,
a = x ^ y,b = y. - Step 2:
b = a ^ b = (x ^ y) ^ y = x. Nowb = x. - Step 3:
a = a ^ b = (x ^ y) ^ x = y. Nowa = y.
The swap works because x and y "cancel out" in the right order. It's a bit of algebraic sleight-of-hand, made possible by XOR's self-inverse property.
4. The overflow problem with arithmetic
If a and b are both positive and their sum exceeds INT_MAX (about 2.1 billion on typical systems), the addition a + b overflows. In C, signed integer overflow is undefined behavior — the compiler can technically do anything, though in practice on two's-complement systems it wraps around to a negative number. The subsequent subtractions may still produce the correct swap (because the wrap-around and the two's-complement arithmetic are consistent), but it's not portable, and a compiler could legitimately produce incorrect code.
The XOR method has no overflow problem, because XOR is a bit-level operation with no carries. Any pair of integers can be safely XOR-swapped without overflow. This is one reason the XOR method is sometimes preferred over the arithmetic method — though for production code, using a temporary variable is the safest choice of all.
5. The aliasing problem
Both methods fail if a and b are the same variable, i.e., they alias the same memory location. For example:
int x = 5;
int *p = &x;
int *q = &x; /* p and q point to the same location */
If you try to swap through p and q with any of these methods, you'd be modifying the same variable through two names — and the intermediate operations corrupt the value. For example, in the arithmetic method: *p = *p + *q; writes 10 to x. Then *q = *p - *q; reads 10 from x (through both p and q), computes 10 − 10 = 0, writes 0 to x. Then *p = *p - *q; computes 0 − 0 = 0, writes 0. Result: x = 0, not 5. The swap fails.
The temporary-variable swap doesn't have this problem: int temp = *p; *p = *q; *q = temp; works correctly even when p == q, because the intermediate value is stored in a separate variable, not in the aliased location.
6. Why the temporary is still the right choice
The no-temp tricks are clever, and they demonstrate interesting properties of arithmetic and bitwise operators. But in real code, the temporary-variable swap is the right choice:
- Clarity:
temp = a; a = b; b = temp;is obvious to any reader. The XOR version is obscure — a reader has to think about whether it's correct. - Correctness: the temporary works for any type, including floating-point, structures, pointers, and arrays of any size. XOR only works for integers.
- No overflow: the temporary doesn't do arithmetic on the values, so overflow is never an issue.
- Aliasing: the temporary works even when the two values are in the same location. The tricks don't.
The memory savings of one temporary variable (typically 4 bytes for an int, 8 for a double, or the size of the type) are negligible. On a machine with gigabytes of RAM, saving 8 bytes is meaningless. The cost of clarity and correctness is much higher than the benefit of memory savings.
🎯 Key idea: the temporary-variable swap is the right choice in real code — it's clear, correct for any type, and has no hidden caveats. The no-temp tricks are fascinating and worth learning, but they're puzzles, not optimizations. Use the temp; enjoy the tricks.
Frequently Asked Questions
1. Which is faster — the temp variable or the XOR trick?
On modern compilers, they're essentially the same. The compiler recognizes both patterns and emits efficient code — often the same code for both. The "memory savings" of the no-temp trick are eliminated by the compiler's register allocation, which puts both variables and the intermediate values in CPU registers. So there's no performance advantage to either method — pick the one that's clearer to read, which is the temporary variable.
2. Why doesn't the XOR trick work for floats?
Because XOR is a bitwise operator, which only operates on integer types. Floats are stored as IEEE 754 floating-point values (sign bit, exponent, mantissa), and bitwise operations on them don't have the same algebraic properties as on integers. There is no equivalent "reversible" bitwise operation for floats that would allow the swap trick. So for floats, you must use a temporary (or arithmetic — which works for floats, since + and − are defined for them).
3. What happens if a and b are the same variable?
Both tricks fail. For the XOR version: a = a ^ a = 0; then b = a ^ b = 0 ^ 0 = 0; then a = a ^ b = 0 ^ 0 = 0. So both end up 0. For the arithmetic version: a = a + a = 2a; then b = a - b = 2a - a = a; then a = a - b = a - a = 0. Both end up 0. The temporary-variable swap works fine in this case (because temp is separate), so it's the safe choice when aliasing is possible.
4. What's the overflow problem with the arithmetic swap?
If a + b exceeds INT_MAX (or, for subtraction, drops below INT_MIN), the arithmetic overflows. In C, signed integer overflow is undefined behavior — the standard doesn't specify what happens. In practice, on two's-complement systems, the result wraps around to a negative number, and the subsequent subtractions often still produce the correct swap. But this is not portable, and a compiler is technically allowed to produce incorrect code. The XOR method has no such issue (XOR never overflows), and the temporary variable has no such issue either.
5. When would you actually use the no-temp swap?
Almost never, in production code. The trick is useful in two contexts: (a) as an interview or viva question to demonstrate understanding of operators, and (b) in code golf or obfuscated code contests, where terseness is the goal. It's also useful in embedded systems where every byte of RAM is precious (very rare nowadays, given modern microcontrollers typically have at least a few KB). But for general-purpose software, the temporary-variable swap is safer and clearer. Use the temp.
6. Why does the arithmetic method work even though a + b "loses" information?
It doesn't really lose information — the sum a + b, together with one of the original values, is enough to recover the other. The full state after step 1 is (a + b, b). From this, you can recover b (= b, unchanged) and a (= (a + b) − b). Step 2 uses that: b becomes (a + b) − b = a. Then step 3 uses the new (a + b, a) to recover b = (a + b) − a. Each step preserves enough information to recover the originals; no information is lost, it's just rearranged. The same applies to XOR, with XOR's inverse property replacing subtraction.
💡 Tip: once this works, try the assignment with pointers instead of integers. int *p = &a; int *q = &b; — the swap is *p = *p + *q; *q = *p - *q; *p = *p - *q;. Same trick, but now applied through pointers. Then try it with p == q (both pointing to the same variable) — see the failure mode first-hand. That's why the temporary variable exists.