How to swap two variables… by themselves?

Phuc Truong
1 min readApr 10, 2021

It seems like a simple-and-traditional question. I guess some of you have faced this problem. Maybe when you try to implement a sorting algorithm by yourself, you will need it.

Face/Off — Source

We can use default function of the language or write it, like:

void swap(int &a, int &y)
{
int temp = b;
a = b;
b = temp;
}

And there is a question, do we need an extra variable temp ?

No, it isn’t. But how?

Firstly, in some languages, we have a, b = b, a and the values of them are switched. However, in other framework which does not support this annotation, can we do that trick again?

Secondly, my answer is YES. Here is the thing:

a = a + b
b = a - b
a = a - b

Now, let’s test it in Python:

>>> a = 1
>>> b = 2
>>> a = a + b
>>> b = a - b
>>> a = a - b
>>> a
2
>>> b
1

and done. If you have any solution, please tell me in the comment.

Have fun!

--

--