Swapping two variables normally implies that you have to use a third temporary variable as a buffer. But this prove of concept code shows that this can be done without a third variable using the XOR operator.

But you ask yourself what that code is good for?

  • In cases you don't have much RAM but much FLASH ROM for program code.
  • If you have very big values... have you?

The code

Swap variable a and b with xor operation:

int main() {
    int a=123;
    int b=23;
    printf("%i %i\n", a, b);
    a = a ^ b;
    b = a ^ b;
    a = a ^ b;
   printf("%i %i\n", a, b); 
}

Cmd output

joachim@flixflux:/tmp
15 $ ./xor_swap
123 23
23 123
Powered by MediaWiki