- How to swap two numbers using only
+and− - How to swap two numbers using only XOR (
^) - Why the XOR method is "safer" than addition/subtraction in some cases
- The overflow and aliasing caveats of both methods
- Why the temp-variable version is the standard idiom in production code
Two ways to swap without a temp
The standard way to swap two variables is with a temporary:
a = b;
b = temp;
That's three lines, one extra variable, and it always works. But there are two classic alternatives that avoid the temporary entirely — using arithmetic or using XOR. Both are worth knowing: they're common in puzzle contexts, interview questions, and legacy code, and they illustrate useful properties of the operators involved.
The two methods:
- Addition/subtraction:
a = a + b; b = a − b; a = a − b; - Bitwise XOR:
a = a ^ b; b = a ^ b; a = a ^ b;
Both rely on the trick of storing enough information in a and b combined to reconstruct both original values, then extracting them one at a time.
(a + b) − b = a and (a ^ b) ^ b = a — each method undoes itself, letting you "recover" the original a from the combined value.
Method 1 — addition/subtraction
The idea: temporarily store the sum in a, then use the sum to reconstruct b's original value (as sum − a_orig), then use the new b to reconstruct a's original value.
Trace with a = 5, b = 7:
| Step | Operation | a | b | Note |
|---|---|---|---|---|
| 0 | — | 5 | 7 | Initial |
| 1 | a = a + b | 12 | 7 | a = 5 + 7 = 12 |
| 2 | b = a − b | 12 | 5 | b = 12 − 7 = 5 (= original a) |
| 3 | a = a − b | 7 | 5 | a = 12 − 5 = 7 (= original b) |
After three steps, a = 7, b = 5 — the values are swapped. No temporary variable was needed. The arithmetic works for any two integers (with the overflow caveat below).
Method 2 — bitwise XOR
The idea: XOR has the property x ^ x = 0 and x ^ 0 = x. So XORing with the same value twice "cancels out" — exactly what we need to reconstruct an original value after combining two variables.
Trace with a = 5, b = 7 (binary 0101 and 0111):
| Step | Operation | a | b | Note |
|---|---|---|---|---|
| 0 | — | 5 (0101) | 7 (0111) | Initial |
| 1 | a = a ^ b | 2 (0010) | 7 (0111) | a = 0101 ^ 0111 = 0010 |
| 2 | b = a ^ b | 2 (0010) | 5 (0101) | b = 0010 ^ 0111 = 0101 (= original a) |
| 3 | a = a ^ b | 7 (0111) | 5 (0101) | a = 0010 ^ 0101 = 0111 (= original b) |
After three steps, a = 7, b = 5 — swapped. The XOR method works for any two integers, signed or unsigned, because XOR operates on the bit patterns directly.
Complete C Programs
Program 1 — using addition/subtraction:
Program 1: Swap using + and −
#include <stdio.h>
int main(void) {
int a, b;
printf("Enter two integers: ");
scanf("%d %d", &a, &b);
printf("Before swap: a = %d, b = %d\n", a, b);
a = a + b;
b = a - b;
a = a - b;
printf("After swap: a = %d, b = %d\n", a, b);
return 0;
}
Program 2 — using bitwise XOR:
Program 2: Swap using XOR
#include <stdio.h>
int main(void) {
int a, b;
printf("Enter two integers: ");
scanf("%d %d", &a, &b);
printf("Before swap: a = %d, b = %d\n", a, b);
a = a ^ b;
b = a ^ b;
a = a ^ b;
printf("After swap: a = %d, b = %d\n", a, b);
return 0;
}
Both programs produce identical output — the choice between methods is stylistic. The XOR version is often called the "classic XOR swap."
Program Output
Running either program with 5 7:
Enter two integers: 5 7
Before swap: a = 5, b = 7
After swap: a = 7, b = 5
Values are swapped. Correct.
With negative numbers:
Enter two integers: -3 8
Before swap: a = -3, b = 8
After swap: a = 8, b = -3
Both methods handle negatives correctly. The XOR method handles any signed value uniformly (bit pattern manipulation); the addition method also works, as long as intermediate sums don't overflow.
With equal values:
Enter two integers: 5 5
Before swap: a = 5, b = 5
After swap: a = 5, b = 5
Identical values produce identical "swapped" values — which makes sense, since swapping equal values has no visible effect.
Step-by-Step Explanation
1. Reading inputs: scanf("%d %d", &a, &b) reads two integers into a and b. The & is the address-of operator.
2. Why addition/subtraction works: In step 1, a becomes a + b. In step 2, b becomes (a + b) − b = a — the original a. In step 3, a becomes (a + b) − a = b (using the new b, which is the original a). Both original values are recovered.
3. Why XOR works: In step 1, a becomes a ^ b. In step 2, b becomes (a ^ b) ^ b = a ^ (b ^ b) = a ^ 0 = a — the original a. In step 3, a becomes (a ^ b) ^ a = b ^ (a ^ a) = b ^ 0 = b — the original b. Both original values are recovered.
4. Why XOR is "safer": The XOR method doesn't involve any arithmetic overflow. XOR always produces a value that fits in the type, so no wraparound happens mid-swap. The addition/subtraction method, on the other hand, can overflow at step 1 if a + b exceeds the type's range. For example, if a = 2,000,000,000 and b = 2,000,000,000 (both positive, both fitting in int), their sum overflows and gives a negative number, and the subsequent steps produce wrong results.
5. The aliasing problem: Both methods fail when a and b refer to the same variable (i.e., swap(&x, &x) in a pointer-based version). If a and b are the same memory location:
- XOR:
a = a ^ a = 0, thenb = 0 ^ 0 = 0(butbis the same asa), thena = 0 ^ 0 = 0. Both become 0. - Addition:
a = a + a = 2a, thenb = 2a − a = a, thena = 2a − a = a. Actually this works — it producesaunchanged.
Wait — the XOR aliasing case is the classic bug: if both operands point to the same location, XOR zeroes both. But in our single-variable-pair program, a and b are distinct variables, so this isn't an issue. It becomes an issue in swap(int *p, int *q) when p == q.
6. Compiler optimizations: Modern compilers recognize both swap idioms and may optimize them back to the temp-variable version (or even a single instruction on some architectures). The "no temp variable" claim is more of a puzzle-piece than a performance optimization — using temp is almost always at least as fast and clearer.
7. When to use which: For general code, use the temp-variable swap — it's clear, correct, and safe. Use the XOR swap if you're specifically solving a puzzle that forbids a temp variable, or if you're working in a context where temp registers are at a premium (some assembly-language contexts, but almost never C). Use addition/subtraction only if you're handling values that you know can't overflow. In production code, "swap without temp" is nearly always a red flag — it's clever but fragile.
temp. The three-line temp swap is what every experienced programmer writes, and what every compiler optimizes best.
Warnings and caveats
Before reaching for these tricks, know their limitations:
- Overflow. The addition method overflows if
a + bexceeds the type's range. Forint, that's about ±2.1 billion. Two large positive values, two large negative values, or one of each at extreme magnitudes can all overflow. - Aliasing. Both methods fail (in different ways) if
aandbare the same variable. XOR zeroes the value; addition leaves it unchanged (by accident, not design). In pointer-based swap, this happens when the same pointer is passed twice. - Readability. Nobody reading your code expects a XOR swap. Even if it works, it takes longer to understand than the temp-variable version. In a team codebase, clarity usually wins over cleverness.
- Performance. Modern compilers recognize the temp-variable swap and optimize it to the best machine code — often the same as (or better than) the "clever" versions. There's no performance advantage to avoiding
temp. - Undefined behavior. Signed integer overflow is undefined behavior in C. If the addition method overflows, the compiler is not required to produce "wraparound" — it may produce garbage, crash, or optimize away subsequent code. This is a real concern in production code.
The XOR method avoids overflow (XOR is always defined for all bit patterns) but has the aliasing issue. Neither is strictly "safe" in all cases. Use them for learning; use temp for production.
Frequently Asked Questions
1. Which method is better — addition/subtraction or XOR?
XOR is generally considered better for the "swap without temp" puzzle because it doesn't overflow and works uniformly on all bit patterns. Addition/subtraction can overflow with large values, producing wrong results. But for real code, the temp-variable version is best: it's clear, safe, and optimized by the compiler. Choose XOR over +/− if you must avoid temp; choose temp over XOR for production code.
2. What happens with negative numbers?
Both methods handle negatives. The XOR method is straightforward — it operates on the bit pattern, and two's complement preserves the values. The addition method also works: for a = −3, b = 8, step 1 gives a = 5, step 2 gives b = −3, step 3 gives a = 8. Correct. The only concern is overflow, which can affect both positive and negative values (e.g., INT_MAX + 1 overflows, INT_MIN − 1 underflows).
3. Can I swap floating-point numbers this way?
Addition/subtraction works for floats and doubles (with precision caveats — floating-point addition isn't always exact, so the round-trip (a + b) − b may not equal a exactly). XOR does NOT work for floats — the ^ operator is defined only for integers. For floats, use addition/subtraction if you must avoid a temp, but be aware of precision loss; better to just use a temp.
4. Why do people say "XOR swap is dangerous"?
Two reasons. First, if both operands are the same variable (aliasing), XOR zeroes the value. For example, swap(&x, &x) with int *a = &x; int *b = &x; would zero x. Second, the code is non-obvious — future readers might not immediately understand what it does, and might "fix" it wrongly. In team codebases, unfamiliar idioms are a maintenance hazard. The temp-variable version has neither issue.
5. Does the compiler optimize these tricks?
Yes — modern compilers (GCC, Clang, MSVC) recognize both "swap without temp" patterns and can optimize them. In some cases, the compiler generates the same code as the temp-variable version. In extreme cases, it may even inline a single XCHG instruction (on x86). This is another reason the "cleverness" doesn't pay off — the compiler already knows how to swap efficiently, and it doesn't need your help.
💡 Tip: after understanding both methods, try implementing a swap(int *p, int *q) function using pointers, and test it with swap(&x, &x) to see the aliasing bug in action. Then rewrite with a temp variable and observe that swap(&x, &x) works correctly (x is unchanged). This shows why the temp-variable version is the robust choice, and it's a good exercise in pointer reasoning.