0
float x=something();             // set by something that returns float
double x_double = x;             // cast to double
// Assume no optimization can happen across this barrier
float x_float = x_double;        // cast to float

Is it guaranteed that x==x_float ?

EDIT: commentator makes the good point that x!=x_float if is_nan(x). However, it should be guaranteed that is_nan(x) == is_nan(x_float)?

Philipp
  • 957
  • 1
  • 6
  • 20

1 Answers1

4

Yes, it's guaranteed.

§6.2.5 (Types) para 10:

  1. There are three real floating types, designated as float, double, and long double. The set of values of the type float is a subset of the set of values of the type double

§6.3.1.5 (Conversions of real floating types) para 1:

  1. When a value of real floating type is converted to a real floating type, if the value being converted can be represented exactly in the new type, it is unchanged.

Since the values of float are a subset of the values of double, the float's value can be represented exactly as a double so it is unchanged. The resulting double therefore has an exact float representation so it will be converted back unchanged.

As has been pointed out, the fact that the value is unchanged does not mean it will compare equal since it might be a NaN. But both or neither will be NaN.

rici
  • 234,347
  • 28
  • 237
  • 341