In C++ the code has undefined behaviour because side effect of the post-increment operator is not exactly sequenced relative to other operations.
In C# there is such notion as DAS (define assignment state); DAs before Expression i
must be equal to DAS after Expression i - 1
.
The order of calculation of expression x++
or x--
the following.
- Value of
x
is calculated and saved. - The value is used to calculate
x++
orx--
and also saved. - This saved result becomes the result of the operation.
So consider statement
int a = i++ + ++i + i--;
The first expression is i++
. i
is evaluated. Its value is 10
. It is saved as the value of the expression. Then operation ++
is applied. The result of operation is 11
. So the output DAS of i
is equal to 11
. It is the input DAS for the next expression ++i
. Here ++i
is evaluated because there is pre-increment operator. The value is 12
and the output DAS of i
is 12
. The order of evaluation of i--
the same as i++
. So we have
10 + 12 + 12 = 34
and the output DAS of i
of the expression is 11
.
Maybe it is not very clear but the difference between C++ and C# is that C# made the process of evaluation of expressions more deterministic and clear, to avoid undefined behaviour.