#include <stdio.h>
void swap(int *a, int *b) {
if (a != b) { // 确保两个指针不相同,避免将数自我交换
*a = *a ^ *b; // 步骤 1
*b = *a ^ *b; // 步骤 2
*a = *a ^ *b; // 步骤 3
}
}
int main() {
int x = 10, y = 20;
printf("Before swap: x = %d, y = %d\n", x, y);
swap(&x, &y);
printf("After swap: x = %d, y = %d\n", x, y);
return 0;
}
上述代码的二进制计算
原数值
00001010 a = 10
00010100 b = 20
步骤一到步骤二
11100001 -a 步骤1的值
00010100 b
00001010 -b b =10 步骤2的值
步骤二到步骤三
11100001 -a
00001010 -b
00010100 -a a = 20 步骤3的值