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/