I stumbled upon the following example on wikipedia (http://en.wikipedia.org/wiki/Type_conversion#Implicit_type_conversion).
#include <stdio.h>
int main()
{
int i_value = 16777217;
float f_value = 16777217.0;
printf("The integer is: %i\n", i_value); // 16777217
printf("The float is: %f\n", f_value); // 16777216.000000
printf("Their equality: %i\n", i_value == f_value); // result is 0
}
Their explanation: “This odd behavior is caused by an implicit cast of i_value to float when it is compared with f_value; a cast which loses precision, making the values being compared different.”
Isn’t this wrong? If i_value were cast to float, then both would have the same loss in precision and they would be equal.
So i_value must be cast to double.
No, in the case of the equality operator, the “usual arithmetic conversions” occur, which start off:
This last case applies here:
i_valueis converted tofloat.The reason that you can see an odd result from the comparison, despite this, is because of this caveat to the usual arithmetic conversions:
This is what is happening: the type of the converted
i_valueis stillfloat, but in this expression your compiler is taking advantage of this latitude and representing it in greater precision thanfloat. This is typical compiler behaviour when compiling for 387-compatible floating point, because the compiler leaves temporary values on the floating point stack, which stores floating point numbers in an 80bit extended precision format.If your compiler is
gcc, you can disable this additional precision by giving the-ffloat-storecommand-line option.