使用异或交换指针的值
#include <stdio.h> #include <stdlib.h> void inplace_swap(int *x, int *y) { *y = *x ^ *y; *x = *x ^ *y; *y = *x ^ *y; } int main() { int x = 12; int y = 23; inplace_swap(&x, &y); printf("x: %d, y: %d", x, y); return 0; }
对于随意位向量, 有a^a = 0
于是 *x = *x ^ (*x ^ *y ) = (*x ^ *x) ^ *y = *y
*y = *y ^ (*x ^ *y) = *x