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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With