Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Swap using XOR in C++

Swap two numbers with XOR in C++ and no temporary variable: why the three XOR steps work, rotating three values, and the same-variable trap that zeroes it.

IntermediateBitwise Operations ProgramsExample 4 of 5
swap-using-xor.cpp
1#include <iostream>
2using namespace std;
3
4void swapXOR(int& a, int& b) {
5 a = a ^ b;
6 b = a ^ b; // b = (a^b) ^ b = a
7 a = a ^ b; // a = (a^b) ^ a = b
8}
9
10int main() {
11 int a = 10, b = 20;
12
13 cout << "Before swap: a = " << a << ", b = " << b << endl;
14
15 swapXOR(a, b);
16
17 cout << "After swap: a = " << a << ", b = " << b << endl;
18
19 // Multiple swaps
20 cout << "\nMultiple swaps:" << endl;
21 int x = 5, y = 15, z = 25;
22
23 cout << "Before: x = " << x << ", y = " << y << ", z = " << z << endl;
24
25 swapXOR(x, y);
26 swapXOR(y, z);
27
28 cout << "After: x = " << x << ", y = " << y << ", z = " << z << endl;
29
30 // XOR properties demonstration
31 cout << "\nXOR properties:" << endl;
32 int num1 = 12, num2 = 25;
33 cout << "num1 = " << num1 << ", num2 = " << num2 << endl;
34 cout << "num1 ^ num2 = " << (num1 ^ num2) << endl;
35 cout << "(num1 ^ num2) ^ num2 = " << ((num1 ^ num2) ^ num2) << " (back to num1)" << endl;
36 cout << "(num1 ^ num2) ^ num1 = " << ((num1 ^ num2) ^ num1) << " (back to num2)" << endl;
37
38 return 0;
39}

Sample Output

After swap: a = 20, b = 10

Swapped with no temporary.

(num1 ^ num2) ^ num2 = 12 (back to num1)

XORing twice cancels.

In this one

  • The XOR properties that make the swap work
  • How references let the function change the caller's variables
  • Why swapping a variable with itself gives 0
  • Why std::swap is the better choice in real code

How it works

  1. 1

    a = a ^ b.

  2. 2

    b = a ^ b → original a.

  3. 3

    a = a ^ b → original b.

  4. 4

    Swap x and y, then y and z.

  5. 5

    Print XOR properties for 12 and 25.

Dry run: Swap using XOR

a = 10 (01010), b = 20 (10100)

  1. 1.a = a ^ b = 11110 (30)
  2. 2.b = a ^ b = 11110 ^ 10100 = 01010 (10)
  3. 3.a = a ^ b = 11110 ^ 01010 = 10100 (20)
a = 10 (01010), b = 20 (10100)
a = a ^ b = 11110 (30)
b = a ^ b = 11110 ^ 10100 = 01010 (10)
a = a ^ b = 11110 ^ 01010 = 10100 (20)

Edge cases

Same variable

swapXOR(x, x)

x becomes 0, because x ^ x = 0 in the first step. Check &a == &b first.

Equal values in different variables

a = 7, b = 7.

Works fine: both stay 7. Only the same memory location is a problem.

What's going on

XOR can swap two integers without a temporary variable. It relies on three properties: x ^ x = 0, x ^ 0 = x, and the order of XORs does not matter.

swapXOR takes both values by reference, so it changes the caller's variables. With a = 10 and b = 20:

1.a = a ^ b stores the combination of both in a.
2.b = a ^ b is (original a ^ b) ^ b. The two b's cancel, leaving the original a, so b is now 10.
3.a = a ^ b is (original a ^ b) ^ original a. The a's cancel, leaving 20.

The output shows a = 20 and b = 10.

The multiple-swap example chains two swaps. Swapping x and y gives x = 15, y = 5. Swapping y and z then gives y = 25, z = 5. The three values have rotated: 15, 25, 5.

The last part prints the XOR properties directly. 12 ^ 25 = 21, and XORing 21 with either number gives back the other. That "XOR twice undoes it" property is used in simple checksums, in RAID parity, and in the find-missing-number program.

The trick has a well-known trap. If both references point to the same variable, as in swapXOR(x, x), step 1 sets x to x ^ x = 0, and it stays 0. A real swap would leave x unchanged. Guard with if (&a == &b) return;.

In real code, use std::swap(a, b). It is clearer, works for any type, and compilers generate code at least as fast. The XOR swap is worth knowing for interviews and for understanding XOR, not for speed.

The headers come first. <iostream> is there because it provides cout and cin for input/output operations. Leave one out and the compiler stops at the first name it does not recognize.

Understanding XOR Swap

XOR Properties:

a ^ a = 0 (XOR with itself is zero)
a ^ 0 = a (XOR with zero is identity)
(a ^ b) ^ b = a (XOR is reversible)
Commutative: a ^ b = b ^ a

Swap Algorithm:

Uses XOR properties
No temporary variable needed
Three XOR operations
Elegant solution

XOR Swap Algorithm

Three Steps:

1.a = a ^ b
2.b = a ^ b // b = (a^b) ^ b = a
3.a = a ^ b // a = (a^b) ^ a = b

What happens here:

Step 1: Store XOR in a
Step 2: Recover original a in b
Step 3: Recover original b in a
Swaps values using XOR properties

Why It Works

Mathematical Proof:

After step 1: a = a^b, b = b
After step 2: a = a^b, b = (a^b)^b = a
After step 3: a = (a^b)^a = b, b = a
Result: a and b are swapped

XOR Reversibility:

(a ^ b) ^ b = a (recover a)
(a ^ b) ^ a = b (recover b)
XOR is its own inverse

Important Limitation

Same Memory Location:

Don't use if variables are same
a ^ a = 0 (would zero the value)
Always check if different
Use temporary for safety

Example Problem:

swapXOR(x, x) would set x to 0
Must ensure different variables
Check before swapping

When to Use XOR Swap

Good fits:

Embedded systems (limited memory)
Educational purposes
Demonstrating XOR properties
Memory-constrained environments

Not Recommended For:

Modern systems (compiler optimizes)
Readability concerns
Same variable risk
Production code (usually)

Modern Compilers

Compiler Optimization:

Modern compilers optimize swaps
Temporary variable optimized away
XOR swap may be slower
Use standard swap for clarity

Recommendation:

Use std::swap() in production
XOR swap for learning
Understand the concept
Prefer readability

XOR Properties Demonstration

Reversibility:

(a ^ b) ^ b = a
(a ^ b) ^ a = b
XOR can recover original values
Foundation of XOR swap

Understanding:

Helps understand algorithm
Demonstrates XOR power
Educational value
Foundation for other algorithms

return 0;

return 0; closes main and tells the operating system the program finished without an error.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

After a = 6, b = 9, and the first step a = a ^ b, what is a?

Pick an answer to check it.

Question 2

What does swapXOR(x, x) do to x = 5?

Pick an answer to check it.

Questions people ask

Is XOR swap faster than a temp variable?

No. Modern compilers make the temp version as fast or faster.

Can I swap with + and −?

a = a + b; b = a − b; a = a − b; works too but can overflow.

Does it work on doubles?

No. ^ is defined only for integer types.