Why is `i = ++i + 1` unspecified behavior?

You make the mistake of thinking of operator= as a two-argument function, where the side effects of the arguments must be completely evaluated before the function begins. If that were the case, then the expression i = ++i + 1 would have multiple sequence points, and ++i would be fully evaluated before the assignment began. That’s not the case, though. What’s being evaluated in the intrinsic assignment operator, not a user-defined operator. There’s only one sequence point in that expression.

The result of ++i is evaluated before the assignment (and before the addition operator), but the side effect is not necessarily applied right away. The result of ++i + 1 is always the same as i + 2, so that’s the value that gets assigned to i as part of the assignment operator. The result of ++i is always i + 1, so that’s what gets assigned to i as part of the increment operator. There is no sequence point to control which value should get assigned first.

Since the code is violating the rule that “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,” the behavior is undefined. Practically, though, it’s likely that either i + 1 or i + 2 will be assigned first, then the other value will be assigned, and finally the program will continue running as usual — no nasal demons or exploding toilets, and no i + 3, either.

Leave a Comment