문제

I'm very convinced with the explanation I've found that said that i = ++i is not undefined as far as C++0x is concerned, but I'm unable to judge whether the behavior of i += ++i is well-defined or not. Any takers?

도움이 되었습니까?

해결책

The reasoning that makes i = ++i well-defined can equally be used to prove that i += ++i must also be well-defined.

i += ++i is equivalent to i += (i += 1) and the new sequencing rules require that the assignment takes place before the value-computation of the i += 1 sub-expression.
This means that the result of the expression i += ++i must be the same as for i = 2 * i + 1.

Edit: I have to revise my answer, because the behaviour is undefined after all.
The behaviour of i += ++i is undefined, because the value-computations of the sub-expressions i (left-hand side argument) and ++i are unsequenced in relation to each other and one of them contains an update of the object i.

This is not a problem for the expression i = ++i, because there the i on the left-hand side does not undergo an lvalue-to-rvalue conversion, which does happen in the i += ++i case.


On a side-note: Don't write such code in any serious project. It relies too much on exactly knowing the sequencing rules and there will be many people who either don't properly understand the sequencing rules, are unaware of the change in the rules that is the result of DR 637 or get tripped up by missing some important aspects of the expression in question (as happened to me when composing the first revision of this answer).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top