The expression ++i + ++i is an error in C++ (or C, for that matter), the compilers are allowed to do anything at all. It's like reading from uninitialized memory.
Running an undefined program is quite pointless, but in case it would help you understand the scope of the problem, I'll run it on a few more compilers for you:
Expression ++i is lvalue. So the compiler have to write the increased value to i.
So we have
++i + ++i;
The order of evaluation of operands is not important.
So the compiler increases i and writes the new value in the cell occupied by i. i will be equal to 2. Then again the compiler reads i increases it and writes the new value in the cell occupied by i. i will be equal to 3. Then it adds the new value of i to itself and gets 6.
@Cubbi demonstrated that some compilers satisfy the new C++ 11 standard and others not. Compilers that satisfy the new standard return 6. Compilers that does not satisfy the new standard return 5.:)
Just in case anyone takes the above post seriously despite the emoticon, C++11 and C++03, although differently phrased, have effectively identical rules as far as this expression is concerned: it's undefined.
abeginner23235616 wrote:
But can you explain me, how 6 is right?
Everything is right when executing such code. 5. 6. 42. crash. everything. The compiler operates under the assumption that it will never encounter such code (except for the front-end error checking: gcc and clang for example, report this as a warning)
There are only your emotions. The question is not simple as you are trying to represent it.
My point of view is that these two increments are indeterminately sequenced and it is not important which expression will be evaluated first.
Whether the program is defined or not is not related to anyone's emotions.
vlad wrote:
My point of view is that these two increments are indeterminately sequenced and it is not important which expression will be evaluated first.
And the point of view of the C++ standard is that the two increments are unsequenced (using C++11 wording), which is why evaluation of the expression ++i + ++i where i has the type int is undefined behavior.
@Cubbi
And the point of view of the C++ standard is that the two increments are unsequenced (using C++11 wording), which is why evaluation of the expression ++i + ++i where i has the type int is undefined behavior.
I am not sure that it is the point of view of the C++ Standard and not just your point.