English 中文(简体)
C# Compiler Behavior Question?
原标题:C# Compiler Behavior Question?
  • 时间:2009-10-12 18:51:26
  •  标签:

每个人都在以下法典中,在第二次表达之后,结果如何?

        int d = 1;
        d += d++;

之后假设为3个,但零增(++)似乎没有生效,因此保留了2个数值。

是否有这个名字? 是否有其他汇编者支持像C#这样的非固定的增量?

最佳回答

如果你看看一下产生的IL,那么你就看为什么结果为2而不是3。

IL_0000:  ldc.i4.1  // load constant 1 on evaluation stack
IL_0001:  stloc.0   // pop and store value in local 0
IL_0002:  ldloc.0   // load value of local 0 on evaluation stack
IL_0003:  ldloc.0   // repeat, stack is now 1, 1
IL_0004:  dup       // duplicate topmost value on evaluation stack, 
                    // i.e. stack is now 1, 1, 1
IL_0005:  ldc.i4.1  // load constant 1 on evaluation stack
IL_0006:  add       // add two topmost values on stack, 
                    // i.e. 1 and 1 and push result on stack
IL_0007:  stloc.0   // pop and store this value in local 0
IL_0008:  add       // add the two remaining values on the stack
                    // which again happens to be 1 and 1 and push result to stack
IL_0009:  stloc.0   // pop and store this value in local 0

换言之: 储存的最终价值为1和1美元。

(上述法典不是释放模式的建立)

问题回答

它不是ug,而是按预期行事。

+ = 运营商扩大为:

d = d + d++;

这意味着,如果结果被分配到变量上,则++操作者所引发的变化就已经过时了。

如果你以这种方式重写你的法典,就会确定:

int d = 1;
d += ++d;

Take a look at the ++ Operator documentation for an explanation as to why your example behaves the way it does.
Excerpt:

The second form is a postfix increment operation. The result of the operation is the value of the operand before it has been incremented.

正如@Guffa所指出的,这并不是一个ug,它只是说,你在<代码>d上的固定加固业务的结果正在由<代码>+=操作”取代。

我经常收到关于++操作者为“经纪人”的问题;几乎总是因为提出问题的人被用某种语言操作,而行为++没有明确界定,例如C++。 这里,我最近写过这样的假设:

http://blogs.msdn.com/ericfallert/archive/2009/08/10/precedence-vs-order-redux.aspx” rel=“nofollow noretinger”>http://blogs.msdn.com/ericfallert/archive/2009/08/10/precedence-vs-order-redux.aspx

你是否尝试了++d? 之后是否对t d++进行了评估?

我认为,<代码>d++与<代码>++d不同,但存储在<代码>d上的最终结果相同。

沉默的法典是无法预测的。 我建议

d += 2;

d++和++d不同。 还称为“。 选择Isn t Broken.

......这也将成为我为什么认为职位/升级前的操作者与其他操作者表达方式时非常无法阅读的原因。 你描述的行为是正确的,但很难说明,导致误解和ug。

即便是这样说的话,我还是要把这改写如下:

int d = 1;
d += d;
++d;

注意使用提炼前操作员,而不是加固后,以便汇编者认为需要保存旧价值的副本。





相关问题
热门标签