Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this expression produce different results in C# and C++?

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?

like image 231
Bhavesh Avatar asked Nov 27 '10 11:11

Bhavesh


2 Answers

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).

like image 150
fredoverflow Avatar answered Sep 28 '22 15:09

fredoverflow


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.

like image 23
Prasoon Saurav Avatar answered Sep 28 '22 15:09

Prasoon Saurav