Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 912
Dhruvin shah Avatar asked Dec 02 '22 19:12

Dhruvin shah


1 Answers

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.

like image 131
haccks Avatar answered Dec 14 '22 23:12

haccks