Swap your variables without a temp variable

I clearly remember that first course programming class in which the teacher said to us – “…If you need to swap the values of two variables, you always need a third temporary variable to hold the value of the first one while you are setting the value of the second one over the first one…” – In this moment it seemed to be right and it was marked over stone in my mind. In C code it is something like that:

/*Initializations*/
int a,b,temp;
a=1;
b=2;  

/*The classic swap code*/
temp=a;
a=b;
b=temp;

/*Values have been happily swapped! (a==2 && b==1)*/

It was ok until I was having a dinner with some friends from the university and one of them said – “..hey! I was  reading a open source related book and I saw a cool method to swap two variable values without to use a third one!” – He didn’t remember the exact code, only that the technique has XOR operations involved. When I arrived home I ran to my bash shell and started to write a few C lines until I rediscovered the trick. It is really cool, uses the same number of operations but a variable less:

/*The swap code (Initialization are the same) */
a^=b^=a^=b;

/*That’s all! Your variables swapped magically*/

I expect this simple trick make you as happy as it made to me ;-)

No comments yet

Leave a reply