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

1

4
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

Vaudeville answered 14/7, 2014 at 11:14 Comment(5)
Undefined behavior means: 5 is 6. So the output is the same :) (You cannot change i twice without a sequence point in between in C)Alexalexa
You mean the output is 6 in your C compiler. other answers are available because it's undefined behaviour.Lewellen
Probably because they're not the "same logic."Ciccia
It doesn't really matter either way. Only a total idiot would use such constructs in real code.Afflatus
Just curious.. Did you do any research regarding this prior to asking?Alewife
L
17

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.

Lineal answered 14/7, 2014 at 11:17 Comment(3)
does increment//decrement operator not evaluate from right to left?Vaudeville
Do you mean expressions ?Lineal
In C order of evaluation of expressions is not guaranteed.Lineal

© 2022 - 2024 — McMap. All rights reserved.