Compound assignment operators with self in C++

334 Views Asked by At

To compute the square of 2.0, does this code

double a = 2.0;
a *= a;

have well defined behavior? And, equivalently, with all the other compound assignment operations and build-in types.

2

There are 2 best solutions below

0
On BEST ANSWER

It's legal, because (C++11, §1.9/15): "The value computations of the operands of an operator are sequenced before the value computation of the result of the operator" or (C++03, §5/4): "Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored." (In a *= a, the a on the left side is accessed only to determine the value to be stored. And the evaluation of the a on the left side is a "value computation", without side effects.)

1
On

Yes it is.

The only reason to believe the contrary would be an issue with sequence points, but that does not apply here.

1) Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression.

You only modify once, you are good.