Consider the following C++ Standard ISO/IEC 14882:2003(E) citation (section 5, paragraph 4):
Except where noted, the order of evaluation of operands of individual operators and subexpressions of individual expressions, and the order in which side effects take place, is unspecified. 53) Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored. The requirements of this paragraph shall be met for each allowable ordering of the subexpressions of a full expression; otherwise the behavior is undefined. [Example:
i = v[i++]; // the behavior is unspecified i = 7, i++, i++; // i becomes 9 i = ++i + 1; // the behavior is unspecified i = i + 1; // the value of i is incremented
—end example]
I was surprised that i = ++i + 1
gives an undefined value of i
.
Does anybody know of a compiler implementation which does not give 2
for the following case?
int i = 0;
i = ++i + 1;
std::cout << i << std::endl;
The thing is that operator=
has two args. First one is always i
reference.
The order of evaluation does not matter in this case.
I do not see any problem except C++ Standard taboo.
Please, do not consider such cases where the order of arguments is important to evaluation. For example, ++i + i
is obviously undefined. Please, consider only my case
i = ++i + 1
.
Why does the C++ Standard prohibit such expressions?