Friday, February 11, 2011

Swap two variable values code in one line.

First code pattern that comes to my mind when I want to swap two variable value is

int c;
c = a;
a = b;
b = c;

I found this code in every novice programming book, also in my programming class.
But I've heard one challenging problem (for me as a novice) that try to swap without temporary variable (that is c, in my code.) The code uses knowledge technique from logic class.

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

The caret symbol (^) represents bitwise xor.
Recently, I found the code that written it in one line for making it more cool and less understanding that is

a ^= b ^= a ^= b;

Impressed!

2 comments:

tanakorn said...

This comment is for protecting myself from python fan. I know that python can swap variables in one line too with cool and readability.

b, a = a, b

Unknown said...

you can do that in python with

a,b = b,a