赋值链 - C#和C ++之间的差异 [英] Assignment chaining - differences between C# and C++

查看:89
本文介绍了赋值链 - C#和C ++之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图向我公司的一位受访者提出编程问题,然后我挖出了一个旧的C ++问题。 它故意模糊,并且意味着候选人是否可以读取错误的代码,但我没想到代码在转换为C#时不能工作
。    C ++代码使用XOR交换两个值,它是一个非常简单的代码段:

I was trying to give a programming problem to an interviewee at my company and I dug out one of my old C++ problems.  It's intentionally obscure and meant to see if the candidate could read bad code, but I did not expect the code to not work when translated to C#.   The C++ code swaps two values using XOR, and it a pretty simple snippet:

代码吐出" a = 8 b = 3 "正如所料。 但是,如果我使用System将其转换为C#:

The code spits out "a=8 b=3" as expected.  However, if I translate this to C#:

代码吐出" a = 0 b = 3 ",与C ++不同。 有趣的是,如果我删除了分配链,并将其分为3个分配,如下所示:

The code spits out "a=0 b=3", which is different than the C++.  Interestingly enough, if I remove the assignment chaining, and break it into 3 assignments as below:

现在我得到了" a = 8 b = 3 "我所期待的。 所以,我的问题是赋值链在C#中的语义与在C ++中的语义不同吗?

Now I get the "a=8 b=3" that I expected.  So, my question is does assignment chaining have different semantics in C# than it does in C++?

推荐答案

在C#中赋值是正确的关联就像在C ++中一样。所以在这方面他们是一样的。因此,这在C ++和C#中都是一样的。

Assignment is right associative in C# just like it is in C++. So in that regard they are the same. Hence this works the same in both C++ and C#.

a = b = c;

复杂的是组合部分。文档非常清楚,给定形式的任何组合运算符op = b(通常)等效于a = a op b,其中a仅被计算一次并且其结果被存储。因此,编译此代码
会产生以下结果。

Where things get complicated is the combination part. The documentation is very clear that given any combination operator of form a op= b is (generally) equivalent to a = a op b where a is evaluated only once and its result is stored. Compiling this code therefore results in the following.

int a = 3;
int b = 8;

int num = a;
int num1 = a ^ b;
a = num1;

int num2 = b ^ num1;
b = num2;

a = num ^ num2;

如您所见,编译器将左值存储到临时变量中,计算^然后存储结果进入原始变量。对于下一组值,它使用先前计算的结果(此处为标准表达式优化)
并将其存储到b中。最后它是a的原始值,它具有已缓存的计算值。

As you can see the compiler stores the left value into a temp variable, evaluates the ^ and then stores the results into the original variable. For the next set of values it uses the result it previously calculated (standard expression optimization here) and stores that into b. Finally it ^ the original value of a with the calculated value that it had cached.

就语言而言,这似乎是一个有效的实现。有人可能会争辩说,在最后一个表达式中它应该使用a的当前值而不是缓存值,但我认为规范不会以某种方式澄清。你可以考虑把这个写成C#编译器的bug,看看MS有什么说法,但我怀疑它是按设计工作的。

As far as the language goes this appears to be a valid implementation. One could argue that in the last expression it should be using the current value of a instead of the cached value but I think the spec would not clarify one way or the other. You could consider writing this up as a bug against the C# compiler and see what MS has to say but I suspect it is working as designed.


这篇关于赋值链 - C#和C ++之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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