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
inline
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'.
Comments?
1 comment:
TSTS (Too Stunned To Speak - BTW, I am patenting this one :) )
Post a Comment