I have tried the following code in both C# and C++:
int a = 5;
int b = (a++)+(++a)+(a--)+(--a);
I noticed that the result of b
is different in C# and C++. In C#, I got 23. In C++, I got 20.
Why is this so? Why would an identical expression produce different results in C# and C++? Is this because the two languages have different operator precedence rules?
C# evaluates this from left to right. In C++, funny expressions such as yours invoke undefined behavior, because you are changing a variable and reading it again without an intervening sequence point.
This means that different compilers (or even the same compiler with different optimization settings) are allowed to (and typically will) produce different results for (a++)+(++a)+(a--)+(--a)
.
The expression has well-defined behavior in C# (evaluation from left to right)
In C#, the output would be 24 (not 23)
int b = (a++)+(++a)+(a--)+(--a);
// 5 + 7 + 7 + 5 = 24
In C++, the expression invokes Undefined Behaviour because a
is modified more than once between two sequence points.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With