为什么`j的输出= + 1 + + +我;'在C#和C有什么不同?

问题描述:

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

该程序的输出是 6 在C.But当我用同样的逻辑,C#,
输出 5

The output of this program is 6 in C.But when I use the same logic for C#, the output is 5 .

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

I want to know the reason why the same logic behaves differently in two different languages

在C#中的规则是评估每个SUBEX pression严格从左到右。因此

The rule in C# is "evaluate each subexpression strictly left to right". Therefore

j= ++i + ++i ;  

以及在C#定义,但相同的前pression调用 未定义行为 在C,因为你不能修改变量不止一次之间有两个序列点

is well defined in C# but the same expression invokes undefined behavior in C because you can't modify a variable more than once between two sequence points.

C-FAQ

本标准规定

的previous和下一个序列点之间的对象应具有其存储的值在由前pression 的评价修改最多一次。此外,前一个值是唯一的访问以确定被存储的值。)

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.)

阅读这篇文章由埃里克利珀作进一步的解释:$p$pcedence VS关联性VS订单。

Read this article by Eric Lippert for further explanation: Precedence vs Associativity vs Order.