Search code examples
c++c++11variable-assignmentoperator-precedence

Order of evaluation of assignment subexpressions


The C++11 standard (5.17, expr.ass) states that

In all cases, the assignment is sequenced after the value computation of the right and left operands, and before the value computation of the assignment expression. With respect to an indeterminately-sequenced function call, the operation of a compound assignment is a single evaluation

Does this mean, that the expression:

int a = 1, b = 10;
int c = (a+=1) + (b+=1);

if ( c == 10+1+1+1 ) {
    printf("this is guaranteed");
} else {
    printf("not guaranteed"); 
}

will always evaluate to c==23?


Solution

  • This has always been guaranteed, and the sequenced before rules (or the sequence point rules in pre-C++11) aren't need to determine this. In C++, each (sub-)expression has two important effects in the generated code: it has a value (unless it is of type void), and it may have side effects. The sequenced before/sequence point rules affect when the side effects are guaranteed to have taken place; they have no effect on the value of the sub-expressions. In your case, for example, the value of (a += 1) is the value a will have after the assignment, regardless of when the actual assignment takes place.

    In C++11, the actual modification of a is guaranteed to take place before the modification of c; in pre C++11, there was no guarantee concerning the order. In this case, however, there is no way a conforming program could see this difference, so it doesn't matter. (It would matter in cases like c = (c += 1), which would be undefined behavior in pre-C++11.)