Friday, December 9, 2011

Swap two numeric variables

A simple tips to swap two numeric variables!

Imagine that you have two numeric variables. a and b

int a = 5;
int b = 8;

// Swap numbers
a = a ^ b;
b = b ^ a;
a = a ^ b;

Now the numbers is swapped.

2 comments:

Yosua Jb said...

Cool tip, but it's slow. Slower than conventional use of temporary variable. One may think of it in assembly code terms. Also, that method requires the input at a step depending on the result of the previous step; strictly sequential.

Ali Irawan (Wen) said...

Yes. Mostly temporary variable used most in pratical. :)