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.
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.
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.
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
, thea
on the left side is accessed only to determine the value to be stored. And the evaluation of thea
on the left side is a "value computation", without side effects.)