In real life swapping - XOR Trick vs Temp variable?

Divyansh SharmaDivyansh Sharma
2 min read

Introduction

When we learn about swapping of 2 variables , we find 2 common methods -
1. Using a temporary variable
2. Using the xor trick

#include <iostream>
using namespace std;

void swapWithTemp(int &x, int &y){
    int temp = x;
    x = y;
    y = temp;
}

void swapWithXor(int &x, int &y){
    x = x ^ y;
    y = x ^ y;
    x = x ^ y;
}

int main() {
    int a = 10, b = 20;
    cout << "Before swapping: a=" << a << " b=" << b << endl;

    swapWithTemp(a, b);
    cout << "After swapping with temp: a=" << a << " b=" << b << endl;

    swapWithXor(a, b);
    cout << "After swapping with XOR: a=" << a << " b=" << b << endl;

    return 0;
}

Now the question that arises is that which one is used internally i.e. in different languages and why?

The internal swap implementation in C++ (and most modern languages) does not use the XOR trick. Instead, it typically uses a temporary variable.


Why not XOR swap?

The XOR trick looks clever, but:

  1. Readability: It’s confusing to most programmers compared to a simple temp.

  2. Undefined behaviour: If a and b refer to the same memory location (like swap(x,x) , XOR trick breaks and sets the variable to 0.

  3. Optimisation: Modern compilers optimise temp-variable swap very well; sometimes they even convert it into a register-level XOR/move internally if it’s faster.

1
Subscribe to my newsletter

Read articles from Divyansh Sharma directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Divyansh Sharma
Divyansh Sharma

I am a Full-Stack Developer specializing in the MERN stack and modern web technologies, with a strong focus on backend development and building clean, functional applications that deliver smooth user experiences. Alongside web development, I enjoy working on Linux development, creating desktop applications, and exploring system administration. Currently, I am expanding my skills in AI integration and cloud technologies to design and implement scalable, future-ready solutions.