The premise

If the two numbers to be swapped are in different places (not in the same block of memory), an xOR operation can be used to implement the swap

example

#include <stdio.h>

int main(a)
{
    int a = 12;
    int b = 24;

    / / exchange
    a = a ^ b;
    b = a ^ b;
    a = a ^ b;

    printf("a = %d, b = %d\n", a, b);
    return 0;
}
Copy the code

a = 24, b = 12

The principle of

a = a ^ b

b = a ^ b = a ^ b ^ b = a

a = a ^ b = a ^ b ^ a = b

Two numbers in the same position are swapped incorrectly

A and B are in the same position a = a ^ b = a ^ a = 0 where a and B both point to the same piece of memory, which is 0