Question

The order of evaluation of an expression has always been a source of unspecified behaviors in C++. Has the C++11 standard finally stated what the order of evaluation should be?

Do we now know the values of var1 and var2 of the following expression:

int var1 =10, var2=20;
var1 = var2 = 30;

Will it be var1=30 and var2=30, or var1=20 and var2=30?

Was it helpful?

Solution 2

var1 = var2 = 30;

Both shall be 30 and it's specified by standard. The thing which is not specified is, if assigning operands are complex expression which must be evaluated before assigment, what's the sequence of evaluating them?

(expr1) = (expr2) = x;
   1         2

or

(expr1) = (expr2) = x;
   2         1

OTHER TIPS

No, the new standard does not specify a sequencing or ordering of evaluations of all subexpressions.

The expression a + b + c is grouped grammatically as (a + b) + c, but the three subexpressions a, b and c can be evaluated in any order and the evaluations are not sequenced with respect to each other.

To make this more concrete, consider:

int main()
{
    return printf("Hello") + printf("World") + printf("\n");
}

As for your code: There is no ambiguity there. It is one expression, an assignment expression of the form a = b, where a is the lvalue var1 and b is the subexpression var2 = 30. The fact that you're wondering whether var1 ends up as 20 or as 30 leads me to believe that you're unsure about the operator associativity (for =). That, however, has never been ambiguous and is perfectly well specified in all language variants I can think of. The assigment operator associates on the right, leading to the subexpressions a and b that I have described. This (extremely fundamental) aspect of the language has not been changed in C++11.

If you really want to combine the two problems, you should consider the following expression:

var1 = 10;
(var1 = 20) = (var2 = var1);

Now the final expression is also a = b, but both a and b are non-trivial subexpression whose evaluation is not ordered.

The assignment operator (=) and the compound assignment operators all group right-to-left.

This doesn't tell us anything about evaluation order. It merely means that a = b = c is parsed as a = (b = c) and not (a = b) = c.

1.9/15 still applies:

Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced.

Sequencing rules introduce partial ordering only. In an expression like this:

(x+42) = (y+42)

it is guaranteed that both subexpressions (x+42) and (y+42) are executed before the assignment to the result of (x+42) occurs, but the two subexpressions themselves are not sequenced. Either can be executed before the other one and they can even be interleaved and the order need not be consistent during the execution of the program.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top