Alex Rivera | Logout

Why is `i = i++ + 1` undefined behavior in C++11?

Asked 2012-05-28T02:01:08.620
20

I am reading n3290 draft of C++11 standard (as close as I could get to actual standard text), and I noticed that i = i++ + 1; produces undefined behavior. I have seen similar questions before, but they were answered in terms of older standards (Sequence points). New standard introduces instead concept of Sequencing before/after relation between expression and sub-expression executions.

1.9 13 Sequenced before is an asymmetric, transitive, pair-wise relation between evaluations executed by a single thread (1.10), which induces a partial order among those evaluations. Given any two evaluations A and B, if A is sequenced before B, then the execution of A shall precede the execution of B. If A is not sequenced before B and B is not sequenced before A, then A and B are unsequenced. [ Note: The execution of unsequenced evaluations can overlap. —end note ] Evaluations A and B are indeterminately sequenced when either A is sequenced before B or B is sequenced before A, but it is unspecified which. [ Note: Indeterminately sequenced evaluations cannot overlap, but either could be executed first. —end note ]

1.9 14 Every value computation and side effect associated with a full-expression is sequenced before every value computation and side effect associated with the next full-expression to be evaluated.

1.9 15 Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced. [ Note: In an expression that is evaluated more than once during the execution of a program, unsequenced and indeterminately sequenced evaluations of its subexpressions need not be performed consistently in different evaluations. —end note ] 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

Edit
Report

1 Answer

3

You are confusing value computation with resolution of side effects. While the value of i++ must be computed before the assignment, nothing sequences the side-effect (the modification to i) with respect to the assignment other than the completion of the full expression.

For a contrasting example, have a look at the comma operator: "Every value computation and side effect associated with the left expression is sequenced before every value computation and side effect associated with the right expression." Notice how value computation and side effects are mentioned separately. There is no such rule for assignment.

answered 2012-05-28T02:05:45.007

Your Answer