In below code, result is -6. why?
` int x = 5;
int y = 3;
int result = x++ - (--y + ++x) - y--;`
I think at first, inside parenthesis evaluated, then outside of it in left to right order, but in this way, the result will not be -6. this is order in my opinion:
in number 1 value is 6 and x is 6
in number 2 value is 2 and y is 2
in number 3 value is 6 and x is 7
in number 4 value is 2 and y is 1
in number 5,6,7 expression is 6 - 8 - 2 = -4 which is not equal -6;
in terms of operator precedence and Operator associativity
To quote the C# specification (ECMA-334, 6th edition, June 2022, §11.4.1):
Operands in an expression are evaluated from left to right.
This means that your initial assumption is not correct: "I think at first, inside parenthesis evaluated".
In this case x++
will be evaluated first; the sequence would look something like this:
x++
is evaluated, returning 5, but saving 6 in x--y
is evaluated, returning 2, and saving 2 in y++x
is evaluated, returning 7 (because x
was 6 from the previous operation)5
(from step 1.) -
9
(from step 4.) = -4
y--
gets evaluated, returning 2, but saving 1 in y-4
(from step 5.) -
2
(from step 6.) = -6
As mentioned in one of the comments (Precedence vs associativity vs order), it's important to differentiate between:
Precedence rules describe how an underparenthesized expression should be parenthesized when the expression mixes different kinds of operators
Associativity rules describe how an underparenthesized expression should be parenthesized when the expression has a bunch of the same kind of operator
Order of evaluation rules describe the order in which each operand in an expression is evaluated