C++ USES an xor operation to exchange the values of two Numbers

  • 2020-06-07 04:59:56
  • OfStack

It is the least expensive method to exchange the value of two Numbers without mediation. The simple principle is that the negative of xor is positive


#include <stdio.h>

int main()
 int a = 11, b = 22;
 printf("a=%d b=%d\n", a, b);
 a = a ^ b;
 b = a ^ b;
 a = a ^ b;
 printf("a=%d b=%d\n", a, b);

gcc test.c -o test

a=11 b=22
a=22 b=11

Related articles: