为什么使用XOR交换值使用该化合物的形式时失败? [英] Why does swapping values with XOR fail when using this compound form?

查看:102
本文介绍了为什么使用XOR交换值使用该化合物的形式时失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现这个code交换两个号码,而无需使用第三个变量,使用XOR ^ 运营商。

I found this code to swap two numbers without using a third variable, using the XOR ^ operator.

code:

int i = 25;
int j = 36;
j ^= i;       
i ^= j;
j ^= i;

Console.WriteLine("i:" + i + " j:" + j);

//numbers Swapped correctly
//Output: i:36 j:25

现在我改变了上述code这相当于code。

Now I changed the above code to this equivalent code.

我的code:

int i = 25;
int j = 36;

j ^= i ^= j ^= i;   // I have changed to this equivalent (???).

Console.WriteLine("i:" + i + " j:" + j);

//Not Swapped correctly            
//Output: i:36 j:0

现在,我想知道,为什么我的code给出不正确的输出?

推荐答案

编辑:好的,知道了。

第一点要提出的是,显然,你不应该反正用这个code。然而,当你展开它,它变成相当于:

The first point to make is that obviously you shouldn't use this code anyway. However, when you expand it, it becomes equivalent to:

j = j ^ (i = i ^ (j = j ^ i));

(如果我们使用更复杂的前pression如 foo.bar ++ ^ = I ,这将是非常重要的 ++ 只计算一次,但在这里,我认为这是简单的。)

(If we were using a more complicated expression such as foo.bar++ ^= i, it would be important that the ++ was only evaluated once, but here I believe it's simpler.)

现在,操作数的计算顺序总是从左到右,所以开始我们得到:

Now, the order of evaluation of the operands is always left to right, so to start with we get:

j = 36 ^ (i = i ^ (j = j ^ i));

这(上图)是最重要的一步。:我们已经结束了与36的LHS为其最后执行的XOR运算。该LHS不是价值Ĵ RHS中进行了评估之后。

This (above) is the most important step. We've ended up with 36 as the LHS for the XOR operation which is executed last. The LHS is not "the value of j after the RHS has been evaluated".

的RHS的评价^涉及一级嵌套的EX pression,所以它变成了:

The evaluation of the RHS of the ^ involves the "one level nested" expression, so it becomes:

j = 36 ^ (i = 25 ^ (j = j ^ i));

然后看着嵌套的最深层次,我们可以替代两个 I Ĵ

j = 36 ^ (i = 25 ^ (j = 25 ^ 36));

...变成

j = 36 ^ (i = 25 ^ (j = 61));

在RHS分配到Ĵ第一次出现,但随后的结果是在年底覆盖无论如何,所以我们可以忽略 - 有没有进一步的评估Ĵ最后分配前:

The assignment to j in the RHS occurs first, but the result is then overwritten at the end anyway, so we can ignore that - there are no further evaluations of j before the final assignment:

j = 36 ^ (i = 25 ^ 61);

这是相当于现在:

i = 25 ^ 61;
j = 36 ^ (i = 25 ^ 61);

或者

i = 36;
j = 36 ^ 36;

这已经成为:

i = 36;
j = 0;

我的认为的这是正确的,并且它得到正确的答案......对不住埃里克利珀如果一些关于评估订单的详细信息稍微偏离:(

I think that's all correct, and it gets to the right answer... apologies to Eric Lippert if some of the details about evaluation order are slightly off :(

这篇关于为什么使用XOR交换值使用该化合物的形式时失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆