Let's have this piece of code:
int a = 1;
int b = ++a + ++a;
In C++ (VS 2010) the result is: b = 6 but in C# the result is: b = 5
What's going on there? Why are the results different?
Let's have this piece of code:
int a = 1;
int b = ++a + ++a;
In C++ (VS 2010) the result is: b = 6 but in C# the result is: b = 5
What's going on there? Why are the results different?
It's undefined behaviour
in C++. You are trying to modify value more than one time without sequence points
(per C++98/03 standards).
About C++11
The value computations of the operands of an operator are sequenced before the value computation of the result of the operator. If a side effect on a scalar object is unsequenced relative to either another side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined.
Examples:
i = v[i++]; // the behavior is undefined i = i++ + 1; // the behavior is undefined
In C++, int b = ++a + ++a
is undefined behaviour so you can expect any result.
C# and C++ are different languages, with different semantics.
C# decides to first execute first one ++a, then the other ++a and finally the addition of these two expressions, hence the result is 5.
In C++ you have undefined behaviour. The result could be 2, 3, 4, 5, 6, 34500 or any other. Another possible outcome is Matthew Watson drinking all the beer in his fridge. Anything can happen, actually.
It doesn't make sense, in general, to expect the same behaviour from two different languages. Each one follows its own rules.
Note: See this question Pre & post increment operator behavior in C, C++, Java, & C# for further cross-language discussion.