Swap Two Variables Without a Third One in C++

ยท

2 min read

Have you ever wondered if it's possible to swap the value of two variables in C++ without using a third one? Turns out, it's possible and it's not even that hard...

First let's say that we have two integers stored in two separate variables, like this:

int a = 3;
int b = 5;

And if we wanted to swap the values:

int c = a;  // 3
a = b;      // 5
b = c;      // 3

... which is kinda clunky, as we're creating another variable in the process. But then here's a bit harder-to-read but more interesting way to do it using the exclusive-or operator, ^:

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

This works by using exclusive-or in combination with pointers. Let's say we now want to make a function which takes two integer pointers as parameters and swaps their values:

#include <iostream>

void swap(int *a, int *b) {
    *a ^= *b;
    *b ^= *a;
    *a ^= *b;
}

int main() {
    int a = 3, b = 5;
    swap(&a, &b);
    std::cout << "A: " << a << std::endl
              << "B: " << b << std::endl;
    return 0;
}

There's still something wrong with our swap function: if both variables refer to the same memory location, using the function may result in undefined behavior. To avoid that, we can perform a simple check at the beginning like this:

if (x != y) {
    *a ^= *b;
    *b ^= *a;
    *a ^= *b;
}

If we now compile and run the program, it should print out the following:

A: 5
B: 3

While the "clever" method avoids creating another variable, it's definitely not as clean and as readable as the first one. It's cool to show nonetheless, as it demonstrates the power of pointers.