# Swapping two variables

Some time ago, I had a chat with a few of my friends during a yam cha session on interview questions. One of my friends mentioned that he knew of someone who likes to ask interviewees to demonstrate a way to swap two variables. And according to my friend, most of the fresh graduates are not able to answer the question correctly. 🙂 This really surprises me. Last week, I interviewed a fresh graduate from MIT, he is able to answer the question very brilliantly. I’m very much impressed. This is what he answered:

The best way to swap two variables is to use a temporary variable. He wrote this on a piece of paper:

int a = 0, b = 0, temp = 0;

temp = a;
a = b;
b = temp;

Okay. This is what I would answer if someone asked me this question. Next, he wrote the following in the same piece of paper:

int a = 0, b = 0;

a = a + b;
b = a – b;
a = a – b;

in which he further summarized into:

a = a-(b=(a=a+b)-b);

and

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

Finally, at the end he wrote this:

#define swap(type,a,b) type temp;temp=a;a=b;b=temp;

and

#define swap(a,b) a^=b^=a^=b;

Well.. What I have to say? 🙂 Pretty impressive for a fresh graduate of Computer Science.