如果变量是相同的存储位置,为什么 XOR 交换算法会失败,但如果变量是相同的值则不会
Why does XOR swap algorithm fail if variables are the same storage location, but not if variables are the same values
如果我对相同的值使用 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 运算时,交换会失败(第一个参数会变成零)。
编辑:更清楚 "it fails" 的意思
让我们 运行 一步一步地讨论这两种情况。
案例 #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
location 保存值,它能够产生正确的结果。现在,让我们看看案例 #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。
如果我对相同的值使用 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 运算时,交换会失败(第一个参数会变成零)。
编辑:更清楚 "it fails" 的意思
让我们 运行 一步一步地讨论这两种情况。
案例 #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
location 保存值,它能够产生正确的结果。现在,让我们看看案例 #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。