1

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.

levzettelin
  • 2,600
  • 19
  • 32

2 Answers2

2

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.

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
  • The code is legal, but not for the reasons you quote. In particular, you ignore the sentence immediately following the one you quote, which says that you cannot (always) access the variable otherwise. The classical example would be something like `f( a, ++ a )`, where `a` is only modified once, but the expression still has undefined behavior. – James Kanze May 28 '14 at 13:10
2

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

James Kanze
  • 150,581
  • 18
  • 184
  • 329