May 16, 2004 11:23 PM
Swapping two variables without using a third variable seems to be one of the most frequently asked viva questions for C/C++ programming lab. It's easily done using addition and subtraction. Here's another cool way to do it:

void swap(int *a, int *b)
{
  *a^=*b;
  *b^=*a;
  *a^=*b;
}

'^' stands for XOR operation. In assembly, often registers are cleared to zero using XOR. This can be done by XORing the value of register with it's own value.

CategoryC

Copyright © 2004-2011 Anirudh Sasikumar. All rights reserved.
Last Updated: January 21, 2005 4:38 PM