The first result (2) is pretty obvious, because
a
is incremented two times and decremented two times. Hence
a
has afterwards the same value as before.
The second result (9) is the one that is not so easy to see. The value of
b
depends on the time when the compiler chooses to do the post-increment and post-decrement operations. Your compiler has chosen to them after the entire expression has been completed. Hence b is computed as:
b = 2 + 2 + 3 + 2;
Note that with pre-increment and pre-decrement operations the compiler has no other choice than doing them right away. Hence the last two values are 3 and 2.
As Ron has correctly pointed out in solution 1, the result of this expression is actually undefined. The compiler could have chosen to perform the post-increment and post-decrement operations at an earlier time and that could have resulted in:
b = 2 + 3 + 3 + 2;
It certainly is no good idea to write statements like this. The case here is a little constructed just to demonstrate what
can happen if you abuse the post-increment/decrement operators.