Monday, April 11, 2005

Swapping and temporaries

Has anyone ever asked you this? "swap two integers without using temporary variables".
Well, here is the answer that most people give

a = a^b;

b = a^b;

a = a^b;

where 'a' and 'b' are the variables to be swapped.
Lets look at the traditional approach for swapping two variables


swap(long *a, long *b)


int tmp = *a;

*a = *b;

*b = tmp;


The second version and the first version both use three "C" statements to swap.
The first version will not work for non-scalar types. It will work only for integers, longs, characters and other integral types (called scalars). The second version is easier to maintain and can be extended to cover other types (using templates for example).

On some architectures a = a^b, a^b is stores the result in a temporary and then assigned to 'a'.

Post a Comment