如果我使用具有相同值的 XOR 交换算法,交换不会失败:
#include <stdio.h>
int main()
{
int x = 10, y = 10;
x = x ^ y;
y = x ^ y;
x = x ^ y;
printf("After Swapping: x = %d, y = %d", x, y); // prints "After Swapping: x = 10, y = 10"
return 0;
}
如果我使用指针,交换失败(x 将为零(:
#include <stdio.h>
void swap(int *xp, int *yp)
{
*xp = *xp ^ *yp;
*yp = *xp ^ *yp;
*xp = *xp ^ *yp;
}
int main()
{
int x = 10;
swap(&x, &x);
printf("After swap(&x, &x): x = %d", x); // prints x == 0
return 0;
}
算法是否应该以相同的值失败?如果我只使用布尔代数,当我进行第一次 XOR 运算时交换将失败(第一个参数将变为零(。
编辑:更清楚地说明"它失败"的含义
让我们逐步运行这两种情况。
情况 #1:2 个变量,相同的值
x y
10 10
*run x = x^y*
0 10
*run y = x^y*
0 10
*run x = x^y*
10 10
在这种情况下,y
位置保存该值,它能够产生正确的结果。现在,让我们看看案例 #2。
案例#2:一个位置,比如x。
xp = &x yp = &x
10 10
run *xp = *xp ^ *yp;
0 0 //the value at xp is changed but since locations xp and yp are same, pointing to variable x, both will hold same values at all times.
对于所有未来的语句,0^0 给出 0。因此,o/p。