Order of evaluation of assignment subexpressions

旧巷老猫 提交于 2019-12-11 11:02:36

问题


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?


回答1:


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.)




回答2:


The expression

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

(edit: added the missing brackets, I think this is what you intended)

has the following subexpressions

(1) a+=1
(2) b+=1
(3) (1)+(2)
(4) c = (3)

The order in which (1) and (2) are evaluated is unspecified, the compiler is free to choose any order it likes.

Both (1) and (2) must be evaluated before the compiler can evaluate (3).

(3) must be evaluated before the compiler can evaluate (4).

Now as the order of evaluation of (1) and (2) does not matter, the overall result is well defined, your code will always yield 13 and print "this is now standard". Note that is has always been this way, this is not new with C++11.




回答3:


In your example the compiler shall issue an error because the priority of the addition operator is higher than priority of the assignment operator. So at first 1 + b will be calculated and then there will be an attempt to assign 1 to expression ( 1 + b ) but ( 1 + b ) is not an lvalue.



来源:https://stackoverflow.com/questions/19585808/order-of-evaluation-of-assignment-subexpressions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!