swap variable quest

This is an interesting quest given by my friend who working in Intel, during our conversation online.

How to swap two variables ?

Let say A=123 and B=546, how to swap them. So this is a quest, be smart enough not to give a plain solution like create a temporary variable to swap them. First of all my answer sounds a bit stupid. I say if I coded in python,


Okay that is not the expecting answer. Before you look at the solution below, maybe you would like to try to figure out.

Hint: use logic XOR, no additional variable is needed.



XOR is known as exclusive disjunction where the nature of XOR is when 1 XOR 0 will equal to 1 but when 1 XOR 1 will becomes 0. Another important behavior of XOR is when (a XOR b) XOR b will resulting a.

So lets look back at the solution, you will find A XOR B seems to become “something else”, where this “something else” will return A if we XOR B and return B if we XOR A. So first line, A=(A XOR B). Secondly B = (A XOR B) XOR B = A, where we replace the original A into (A XOR B). Last line, A= ( A XOR B) XOR A = B. Seems at second line B already become A, so we replace B as A.

Interesting isn’t it? Look at it few times, if you can’t get it.

6 thoughts on “swap variable quest

  1. I Have another logic for swaping two variables without using temperary variable..
    LET A=10 AND B=20
    A=A+B // A=10+20–> A=30
    B=A-B // B=30-20 —> B=10
    A=A-B // A=30-10 –>A=20


  2. what ever u all said is right but all will failed when the any of them or ( A or B ) is equal to UINT_MAX or INT_MAX or if there addition cross the MAX_LIMIT of integer

  3. even if you overflow with the + – method it will not fail, if overflow and underflow on your architecture do not produce signals and are consistent. (like if you used unsigned numbers). the overflows and underflows cancel out.

  4. The best way to do it is:

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

    Now call SWAP(Number1,Number2) anywhere in your program and it’ll take care of swapping. This is a more elegant way to write the code IMO.

Leave a Reply

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