Previously, I started discussing C compiler warnings, with specific intent to discuss this one:
warning: comparing floating point with == or != is unsafe [-Wfloat-equal]
I presented a simple question — what would this print?
int main()
{
float var1;
var1 = 902.1;
if (var1 == 902.1)
{
printf ("it is!\n");
}
else
{
printf ("it is NOT.\n");
}
return EXIT_SUCCESS;
}
On my Windows 10 computer running GCC (via the free Code:Blocks editor), I get see “it is NOT.” This goes back to an earlier article I wrote about how 902.1 cannot be represented with a 32-bit floating point. In that article, I tested setting a “float” and a “double” to 902.1 and printed the results:
float 902.1 = 902.099976 double 902.1 = 902.100000
As you can see, a 64-bit double precision floating point value can accurately display 902.1, while a 32-bit floating point cannot. The key here is that in C a floating point number defaults to being double precision, so when you say:
var = 123.456;
…you are assigning 123.456 (a double) to var (a float).
float var1;
var1 = 902.1;
var1 (a float) was being assigned 902.1 (a double) and being truncated. There is a potential loss of precision that a compiler warning could tell you about.
If, with warnings enabled, comparing a floating point using == (equal) or != (not equal) is considered “unsafe,” how do we make it safe?
To be continued…