【问题标题】:Why does XOR swap algorithm fail if variables are the same storage location, but not if variables are the same values为什么如果变量是相同的存储位置,异或交换算法会失败,但如果变量是相同的值则不会
【发布时间】:2017-06-13 07:01:12
【问题描述】:

如果我使用具有相同值的 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;
}

算法是否应该以相同的值失败?如果我只使用布尔代数,当我进行第一次异或运算时交换将失败(第一个参数将变为零)。

编辑:更清楚“失败”的含义

【问题讨论】:

  • “失败”是什么意思?不编译?产生错误的输出?让你的电脑着火了?
  • 你考虑过别名吗? xp 和 yp 指向同一个对象。尝试使用两个变量(可能有 2 个不同的值:x y 为 10 并不能告诉您值已被交换)。
  • 您实际上应该避免通过异或进行交换。因为,对于相同的指针值以及 floatdouble 值,它将失败。
  • 您不能对doublefloat 数据类型进行按位运算。正确的?我在评论中这么说。因为,这不是答案,而是建议。 @MrSmith42

标签: algorithm swap xor


【解决方案1】:

让我们逐步运行这两种情况。

案例 #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。

【讨论】:

  • 案例#1的最后一行应该是10 10
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多