Skip to content

Why is C# skipping the post increment ( ++ ) operator in my code but not C++? #9328

Answered by bernd5
ArinoLane asked this question in Q&A
Discussion options

You must be logged in to vote

x += x++; is the same as x = x + x++;

In CSharp we evaluate always from left to right - first x, than x++;

So x is first 1.
x++ is evaluated to 1, too (it is the post increment operator).
After the evaluation x is incremented by one and assigned to x.

The right hand side of x = x + x++ is evaluated to 1 +1 which is 2.
After the evaluation of the right hand side - the result is assigned to x....
The side effect of evaluating x++ is lost.


In C++ a compiler can evaluate from left to right or from right to left - there we have no strict eval order. This is why your code is UB (undefined behaviour) in C++.

See: https://godbolt.org/z/YjTx9E1nE

When we evaluate from right to left we start with x++

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@jilles-sg
Comment options

Answer selected by 333fred
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants