Search code examples
c++compound-assignment

Compound assignment operators with self in C++


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.


Solution

  • 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.)