Search code examples
c#expressionoperator-precedenceassociativity

result of this expression is not what i learned


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:

  1. ++x
  2. --y
  3. x++
  4. y--
  5. first - from left
    • in middle of expression
  6. last - from left

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


Solution

  • 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:

    1. x++ is evaluated, returning 5, but saving 6 in x
    2. --y is evaluated, returning 2, and saving 2 in y
    3. ++x is evaluated, returning 7 (because x was 6 from the previous operation)
    4. stuff in the parentheses is evaluated (2 + 7) = 9
    5. first subtraction gets evaluated: 5 (from step 1.) - 9 (from step 4.) = -4
    6. y-- gets evaluated, returning 2, but saving 1 in y
    7. final subtraction gets evaluated: -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