我有一个简单的代码片段,它在使用 C++ 编译器和 C# 编译器构建时显示不同的行为。
C#
static void Main(string[] args)
{
int i = 0;
i += i++;
Console.WriteLine(i);
Console.ReadLine();
}
i
的结果是 0
。
从此链接复制。 For i = 0, why is (i += i++) equal to 0?
C++
int main()
{
int i = 0;
i += i++;
cout << i << endl;
}
i
的结果是 1
.
我只是想知道为什么C#和C++的代码输出存在差异。
最佳答案
C#、C++ 和 C 的设计者 made different decisions about how to handle order of evaluation而在 C# the order of evaluation如果从左到右:
Operands in an expression are evaluated from left to right.
副作用也是从左到右发生的。
在 C++ 中情况并非如此,draft C++ standard 1.9
部分程序执行 段落15 说:
Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced.
如果同一标量对象上的副作用相对于另一个副作用进行排序,则结果为 undefined behavior :
[...]If a side effect on a scalar object is unsequenced relative to either another side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined.[...]
草案给出了未定义行为的示例:
i = i++ + 1; // the behavior is undefined
如果我们查看代码中的表达式:
i += i++;
这相当于:
i = i + i++ ;
我们现在可以清楚地看到它调用了未定义的行为,这意味着结果是不可预测且不可依赖的。
关于c# - 程序输出的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22714134/