void inplace_swap(int *x, int *y) { *y = *x ^ *y; //Step 1 *x = *x ^ *y; //Step 2 *y = *x ^ *y; //Step 3 } int main() { int num1 = 100; int num2 = 200; inplace_swap(&num1, &num2); printf("num1=%d\nnum2=%d\n", num1, num2); return 0; }
相比使用一个局部变量来交换两个变量的值,这种方法并无性能上的优点,只是一种对位运算的练习。数组
一个数与它自己异或,结果为0。假设*x = a;*y = b;函数
*x |
*y |
|
Step0 |
a |
b |
Step1 |
a |
a ^ b |
Step2 | a ^ a ^ b ( = b) |
a ^ b |
Step3 | b |
a ^ b ^ b ( = a) |
不过,须要注意,*x与*y指向同一个位置时,*x与*y指向的数变为0性能
例如将一个数组中的元素首尾对调的时,使用下面的函数spa
void reverse_array(int a[], int cnt) { int first, last; for (first = 0, last = cnt - 1; first <= last; first++, last--) { inplace_swap(&a[first], &a[last]); } }
若是数组长度为奇数是,中间的数会变成0
code