Search code examples
c#operator-precedence

Why doesn't the operator precedence "work" with ++/-- i C#?


According to C#'s operator precedence, ++/-- is high on the list (above arithmetic like +, -, etc).

This made me believe that if I had a code looking like this:

int a = 2;
int b = a++;

b "should have" been assigned the value 3 because incrementing is above assignment in the operator precedence list. Why isn't the increment done before assignment?


Solution

  • The result of post-increment (a++) is the value before increment while the result of pre-increment is the value after increment.

    int a = 2; int b = a++; int c = ++a;
    

    Here a++ gives 2 to b, but new value of a is 3. Then another new value 4 of a comes to c.

    The next functions can help to understand:

    int PostIncrement(ref int a) {
      int b = a; a = a + 1; return b;
    }
    
    int PreIncrement(ref int a) {
      a = a + 1; return a;
    }
    
    // and
    
    int a = 2;
    int b = PostIncrement(ref a);
    int c = PreIncrement(ref a);
    

    Then in

    int a = 2;
    int b = a++ + 5;
    int c = ++a - 5;
    

    pre-increment and post-increment execute first, + and - second, and assignment last as prescribed.

    Pre-increment or post-increment takes the neighbour operand only.

    So, more detailed, the execution order in b = a++ + 5 is:

    1. a++
    2. (1) + 5
    3. b = (2)