1

Difference between these when relating it with Operator Priority using prefix and postfix

    // program 01

    int x =10;
    int c = x++ + ++x;
    Console.WriteLine(c); // output will be 22

    // program 02

    int x =10;
    int c = ++x + x++;
    Console.WriteLine(c); // output will be 22

    // program 03

    int x =10;
    int c = ++x + x;
    Console.WriteLine(c); // output will be 22

1 Answers1

7

Here's how these expressions are evaluated:

1:

x++ + ++x;
 |  |  |
 1  3  2

1: increments x to 11, returns value before increment (10)
2: increments x to 12, returns value after increment (12)
3: 10 + 12 = 22

2:

++x + x++;
 |  |  |
 1  3  2

1: increments x to 11, returns value after increment (11)
2: increments x to 12, returns value before increment (11)
3: 11 + 11 = 22

3:

++x + x
 |  | |
 1  3 2

1: increments x to 11, returns value after increment (11)
2: returns value of x (11)
3: 11 + 11 = 22

Worth noting that some C/C++ implementations may evaluate this expression in a different order. This page has examples of undefined behavior that are identical to OP. http://en.cppreference.com/w/cpp/language/eval_order

Michael Gunter
  • 12,528
  • 1
  • 24
  • 58
  • 2
    This answer shows that there no question at all. Everything very logical and have nothing to do with Operator priority, because there is only adding operator – Fabio Nov 01 '16 at 20:00
  • 2
    Well, there is still a valid question here. In ANSI C, expressions are evaluated from right to left. These same expressions in C/C++ will yield different results. In C#, these expressions are evaluated left to right. – Michael Gunter Nov 01 '16 at 20:06
  • 1
    this interesting add up should almost be part of your answer – Antoine Pelletier Nov 01 '16 at 20:07
  • True. I'll verify my comment and update my answer with that extra info. – Michael Gunter Nov 01 '16 at 20:08
  • Tested with Microsoft Visual C++. Both .c and .cpp compilations produce the same results as C#. I could have sworn some of the original C standards said that evaluation was right to left, but either I was mistaken or this has changed in modern times. – Michael Gunter Nov 01 '16 at 20:14