You make a mistake thinking of operator= as a function with two arguments , where the side effects of the arguments should be fully appreciated before the function starts. If so, then the expression i = ++i + 1 will have several points in the sequence, and ++i will be fully evaluated before the start of the assignment. However, this is not so. What is evaluated in the internal assignment operator, and not in the user-defined operator. There is only one point in the sequence in this expression.
The result of ++i is evaluated before the assignment (and before the addition operator), but the side effect is not necessarily applied immediately. The result of ++i + 1 always matches i + 2 , so the value that is assigned to i as part of the assignment operator. The result of ++i always i + 1 , so that is assigned to i as part of the increment operator. There is no sequence point for control whose value should be assigned first.
Since the code violates the rule that “between the previous and next point in the sequence, the scalar object must have its stored value, changed no more than once by evaluating the expression,” the behavior is undefined. In practice, however, it is likely that at first either i + 1 or i + 2 will be assigned, then a different value will be assigned, and finally, the program will continue to work, as usual - nose demons or exploding toilets, not i + 3 either.
Rob Kennedy Dec 07 '09 at 15:30 2009-12-07 15:30
source share