Sitemap

Swapping Two Variables Using XOR: A Beginner-Friendly Guide With a Dangerous Catch

4 min readSep 22, 2025

--

Intro

Let me start by saying: this might sound like a beginner-level problem, but it’s one of those timeless programming exercises that teaches you how computers really handle data. We’re going to talk about swapping two variables a fundamental operation in programming.

Yes, you’ve probably seen it before. But here, we’ll explore a clever twist: the XOR swap algorithm.

The Problem

Swapping the values of two variables is one of the first problems most programmers encounter.

For example, if you have:

a = 5, b = 10

After swapping:

a = 10, b = 5

Simple enough, right? But how do we achieve it?

First Approach (Using a Temporary Variable)

The most straightforward way is to use a third variable as temporary storage.

int temp = a;
a = b;
b = temp;

Here’s what’s happening:

  • We save the value of a into temp.
  • Then we overwrite a with the value of b.
  • Finally, we copy the original a (stored in temp) back into b.

Swap complete.

This works fine, but it requires extra space (the temp variable).

The XOR Swap Trick

Now comes the fun part. There are actually multiple ways to swap without using extra storage, and among them, the XOR swap is one of the fastest (at least conceptually).

The XOR operation (^ in most languages) works at the bit level. Here’s how the swap looks in code:

a = a ^ b;
b = a ^ b;
a = a ^ b;

That’s it. Three lines no temporary variable required.

Understanding XOR at the Bit Level

To understand why this works, let’s quickly revisit XOR:

  • 1 ^ 1 = 0
  • 0 ^ 0 = 0
  • 1 ^ 0 = 1
  • 0 ^ 1 = 1

In short: XOR flips a bit if the other bit is 1, and leaves it unchanged if the other bit is 0.

Get Anmolmeet Singh’s stories in your inbox

Join Medium for free to get updates from this writer.

So what happens step by step?

  1. a = a ^ b
  • a now holds a mix of both values.

2. b = a ^ b

  • Since a is now (a ^ b), XORing it with b cancels out b and leaves us with the original value of a.
  • So now b holds the original a.

3. a = a ^ b

  • At this point, a is (a ^ b) and b is the original a.
  • XORing them gives us the original value of b.
  • Now a holds the original b.

Swap complete.

Proof of Correctness

Let’s formalize the XOR swap using substitution.

After the first line:

a = a ^ b   -----(1)

Second line:

b = a ^ b            //put the value of a from (1)
b = (a ^ b) ^ b
b = a ^ (b ^ b) // using associativity of XOR
b = a ^ 0 // because x ^ x = 0
b = a // now b contains the original value of a ---(2)

Third line:

a = a ^ b             //put the value of a from (1) 
a = (a ^ b) ^ b
a = (a ^ b) ^ a // as b = a from (2)
a = b // now a contains the original value of b

And that completes the swap.

This works because XOR is associative ((x ^ y) ^ z = x ^ (y ^ z)) and commutative (x ^ y = y ^ x), which allows us to rearrange the operations and cancel out identical values. By carefully substituting the values at each step, we see that the original values of a and b are exchanged without using any extra storage.

A Small Catch ⚠️

While this trick is elegant, there’s a catch. If both variables refer to the same memory location, this method breaks down and results in zero. That’s why in practice, the temporary variable method is often preferred for clarity and safety.

Example:

#include <iostream>
using namespace std;

//XOR swap with two variables (unsafe if same variable passed twice)
void xorSwapTwoValues(int a, int b)
{
a = a ^ b;
b = a ^ b;
a = a ^ b;
cout << "Swap result using two values: a = " << a << ", b = " << b << endl;
}

//XOR swap using pointers (unsafe if same variable passed twice)
void xorSwapPointer(int* a, int* b)
{
*a = *a ^ *b;
*b = *a ^ *b;
*a = *a ^ *b;
cout << "Swap result using pointers: *a = " << *a << ", *b = " << *b << endl;
}

int main() {
int x = 7;

// Unsafe: passing the same variable twice
xorSwapTwoValues(x, x); // Output: a = 0, b = 0

// Unsafe: pointer-based swap on the same variable
xorSwapPointer(&x, &x); // Output: *a = 0, *b = 0

// Safe example: pointer swap on distinct variables
int a = 5, b = 10;
xorSwapPointer(&a, &b); // Output: *a = 10, *b = 5

return 0;
}

Output:

Swap result using two values: a = 0, b = 0
Swap result using pointers: *a = 0, *b = 0
Swap result using pointers: *a = 10, *b = 5

Still, the XOR swap is a neat little programming gem and a great example of how bitwise operations can simplify tasks.

If you’re just starting out, understanding this gives you valuable insight into how data is represented at the binary level.

Next time you see two values needing a swap, remember sometimes three lines of XOR magic can do the trick.

--

--

Writing at the crossroads of curiosity, life, and technology.

See more from me