result of this expression is not what i learned

129 Views Asked by At

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

2

There are 2 best solutions below

3
On BEST ANSWER

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

0
On
int result = x++ - (--y + ++x) - y--;

Generates IL that is roughly equivalent to;

var t0 = x;
var t1 = t0 + 1;
x = t1;

var t2 = y;
var t3 = t2 - 1;
y = t3;

var t4 = x;
var t5 = t4 + 1;
x = t5;

var t6 = t3 + t5;
var t7 = t0 - t6;

var t8 = y;
var t9 = t8 - 1;
y = t9;

var t10 = t7 - t8;
int result = t10;

The values you have supplied are evaluated left to right. The binary operations are evaluated when both the left hand and right hand values are available. The parenthesis enforce which values are bound to the left hand and right hand of each binary operation.