In C ++, literals have double precision. In the first examples, the number 3e + 38 is first converted to float in the initialization of the variable, and then returns to double precision in comparison. Conversions are not needed exact, therefore numbers can differ. In the second example, the numbers stay swimming all the time. To fix this, you can change p to double , write
#define x 3e+38f
(which defines a floating literal) or change the comparison to
if (p == static_cast<float>(x))
which performs the same conversion as the initialization of variables, and makes the comparison in single precision.
Also, as noted, comparing floating point numbers with == usually not a good idea, since rounding errors give unexpected results, for example, x*y may differ from y*x .
source share