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
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.
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.
© 2022 - 2024 — McMap. All rights reserved.
i
twice without a sequence point in between in C) – Alexalexa