Open zinking opened 7 years ago
But it does save memory, as you don't need any space besides the source and destination ints
it doesn't, because temp
could easily be optimised into a register.
Should also be noted that xor swap is rarely or never optimized into simply the swap asm instruction; where as with a temp variable it often is. In C++ std::swap is also optimized to the swap instruction.
Maybe it should be noted that xor swap does not work when a & b point to the same pointer/reference (or is the same object).
#include <stdio.h>
void swap( int *a, int *b ) {
int temp;
temp = *a;
*a = *b;
*b = temp;
}
void xor_swap( int *a, int *b ) {
*a ^= *b;
*b ^= *a;
*a ^= *b;
}
int main() {
{
int a = 1;
swap(&a, &a);
printf("%d %d\n", a, a);
}
{
int a = 1;
xor_swap(&a, &a);
printf("%d %d\n", a, a);
}
}
this technique should be discouraged, at least notes should be added. as it is by no means better than the
temp
approach. looking from the execution instruction perspective.