views:

425

answers:

1

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?

+8  A: 
Bart van Ingen Schenau
i += ++i would be equivalent to i = i + ++i; such that i is evaluated only once. But, is it defined which one of i or ++i is evaluated first?
Saurabh Manchanda
@Saurabh: You are right. The difference between `i = ++i` and `i += ++i` is the value-computation of the left-hand `i`, which is unsequenced with the `++i`. This makes the result undefined. I will update my answer accordingly.
Bart van Ingen Schenau
Thanks. I had the same in mind, but wasn't completely sure.
Saurabh Manchanda
@Bart I wonder what "in all cases, the assignment is sequenced ..." precisely means. What exactly is "the assignment"? A compound-assignment is-an assignment. Can we say that a compound-assignment consists of a prvalue evaluation followed by a side effect?
Johannes Schaub - litb
I do agree with your interpretation, though. But I wouldn't bet. Also, I would wish the wording would be a little more clear. "The behavior of an expression of the form E1 op = E2 is equivalent to E1 = E1 op E2 except that E1 isevaluated only once. " <- It isn't apparent to me what exactly "is evaluated only once" means. The two "E1" in that second expressions are evaluated differently: First is glvalue evaluation, second is prvalue evaluation.
Johannes Schaub - litb
@Johannes: The "is evaluated only once" means that the glvalue and the prvalue evaluation have to be done at effectively the same time, or the prvalue evaluation must use the result of the glvalue evaluation. If E1 contains side effects (for example, when it is a function call), then the side effects may only occur once.
Bart van Ingen Schenau
+1 for telling that such a code should never be used.
Stephane Rolland