The Art of Swapping Variables


Improve your writing skills in 5 minutes a day with the Daily Writing Tips email newsletter.

Swapping variables is probably one of the most common operations inside computer programs. But did you know that there are many ways to perform a swamp? Below I’ll talk about some of them.

Using an Extra Variable

The easiest way is to use an extra temporary variable (usually called “temp”) where you store the value of one variable so that you don’t lose it during the first attribution.

int main(){
    int x,y,temp;

    x = 5;
    y = 10;

    temp = x;
    x = y;
    y = temp;

return 0;
}

Without an Extra Variable, Using Some Maths

Here’s a little challenge: how do you swap the value of two variables without an extra one to store the value while you attribute? Try it with pen and paper before reading on.

Answer: Simply add the two values together and store in one variable (x = x + y). Then subtract the value of the second variable from that total (y = x – y). Finally subtract the new value of the second variable from the previous total (x = x – y).

int main(){
    int x,y;

    x = 5;
    y = 10;

    x = x + y;
    y = x - y;
    x = x - y;

return 0;
}

You can do this trick with multiplication and division as well.

int main(){
    int x,y;

    x = 5;
    y = 10;

    x = x * y;
    y = x / y;
    x = x / y;

return 0;
}

Using Bitwise Operations: The XOR Swap

If you haven’t notice, the pattern used in the swap method above is the following:

1. Find two operations that are the inverse of each other
2. Perform the first operation once and the second operation twice to swap the values of two variables.

In happens that the bitwise operator XOR is also the inverse of itself, so we can use it three times to swap the values as well.

int main(){
    int x,y;

    x = 5;
    y = 10;

    x = x ^ y;
    y = x ^ y;
    x = x ^ y;

return 0;
}

You got be careful if you want to use this method in some languages, though. In C, for instance, it won’t work if you perform it on two pointers pointing to the same memory address, as the first XOR will put zeroes on all bits. And if you write the swap as x =^ y =^ x =^ y you might also get undifined behavior.

6 thoughts on “The Art of Swapping Variables

Leave a Reply

Your email address will not be published. Required fields are marked *