Reputation: 2962
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.
Upvotes: 1
Views: 332
Reputation: 153919
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.)
Upvotes: 2
Reputation: 50063
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.
Upvotes: 2