Can a static_cast<float> from double, assigned to double be optimized away?

  • A+

I stumbled on a function that I think is unnecessary, and generally scares me:

float coerceToFloat(double x) {     volatile float y = static_cast<float>(x);     return y; } 

Which is then used like this:

// double x double y = coerceToFloat(x); 

Is this ever any different from just doing this?:

double y = static_cast<float>(x); 

The intention seems to be to just strip the double down to single precision. It smells like something written out of extreme paranoia.


static_cast<float>(x) is required to remove any excess precision, producing a float. While the C++ standard generally permits implementations to retain excess floating-point precision in expressions, that precision must be removed by cast and assignment operators.

The license to use greater precision is in C++ draft N4659 clause 8, paragraph 13:

The values of the floating operands and the results of floating expressions may be represented in greater precision and range than that required by the type; the types are not changed thereby.64

Footnote 64 says:

The cast and assignment operators must still perform their specific conversions as described in 8.4, 8.2.9 and 8.18.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: