I am porting a C++ utility to C#. When I run the following statement in C++, I get the correct operation. When I run the same statement in C#, however…

Does anyone know why ‘begin++’ is executed? The crazy thing is that if I run (i % 2) == 0 with i=0, the Immediate Window returns true.
Operator precedence is irrelevant in this question. It’s evaluation order that causes this behavior.
In C#
i++is evaluated beforei % 2since it’s on the left side. Thusi % 2is false and the right side of the if gets evaluated.First you use precedence to get the syntax tree:
On each node you evaluate the children from left to right. This implies that
i++is evaluated beforei % 2.Eric Lippert has plenty of posts on this, both here on SO, and on his blog:
Personally I’d avoid such code. It’s much nicer to split it into multiple expressions, or even use a plain
ifstatement instead of? :In C++ accessing a variable that was written to without a sequence point in between is undefined behavior. I think
=is no sequence point, so I guess your expression is undefined in C++ and just happened to work.