c# - 为什么 `j=++i+++i;` 在 C# 和 C 中的输出不同?

标签 c# c pre-increment

int i=1,j;
j= ++i + ++i;
printf("%d",j);

这个程序的输出是 C 中的 6。但是当我对 C# 使用相同的逻辑时, 输出是 5

我想知道为什么同样的逻辑在两种不同的语言中表现不同

最佳答案

C# 中的规则是“严格从左到右计算每个子表达式”。因此

j= ++i + ++i ;  

在 C# 中定义良好,但相同的表达式调用 undefined behavior在 C 中,因为您不能在两个 sequence points 之间多次修改变量.

C-FAQ :

The Standard states that

Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored.)

阅读 Eric Lippert 的这篇文章如需进一步说明:Precedence vs Associativity vs Order .

关于c# - 为什么 `j=++i+++i;` 在 C# 和 C 中的输出不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24735290/

相关文章:

c - 在 posix 上限制进程的脚本

java - 如何a=3和b=4?

c++ - 这段代码是如何工作的?

c# - 如何使用 Rhino Mock 模拟扩展方法?

c# - 我可以在 C#.Net Windows 窗体中使用 javascript 吗?

c# - “Grokkable”算法,用于理解指数为 float 的求幂

c# - 是否可以使用 MEF RegistrationBuilder 创建 PRISM ModuleExport?

c - 如何调试像printf这样的标准c库函数?

c - 将文件写入 .c 中的另一个文件

c++ - 预增量运算符的放置在这里会有所不同吗?