Why is the output of `j= ++i + ++i;` different in C# and C?

笑着哭i 提交于 2019-12-23 13:39:13

问题


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

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


回答1:


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

j= ++i + ++i ;  

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:

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

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



来源:https://stackoverflow.com/questions/24735290/why-is-the-output-of-j-i-i-different-in-c-sharp-and-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!