keon / awesome-bits

:computer: A curated list of awesome bitwise operations and tricks
3.06k stars 212 forks source link

xor swap should be discouraged #10

Open zinking opened 7 years ago

zinking commented 7 years ago
a ^= b;
b ^= a;
a ^= b;

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.

calebsander commented 7 years ago

But it does save memory, as you don't need any space besides the source and destination ints

zinking commented 7 years ago

it doesn't, because temp could easily be optimised into a register.

Trippler commented 7 years ago

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.

r-lyeh-archived commented 7 years ago

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);
    }
}