This question already has an answer here:
I was reading this. It contains following C program.
#include<stdio.h>
int main()
{
float x = 0.1;
if (x == 0.1)
printf("IF");
else if (x == 0.1f)
printf("ELSE IF");
else
printf("ELSE");
}
The article says that
The output of above program is “ELSE IF” which means the expression “x == 0.1″ returns false and expression “x == 0.1f” returns true.
But I tried it on different compilers & getting different outputs:
Here is the outputs on various IDEs.
1) Orwell Dev C++: ELSE
2) Code Blocks 13.12: ELSE IF but it gives following warnings during compilation.
warning: comparing floating point with == or != is unsafe.
Why this comparison is unsafe?
3) Ideone.com: ELSE IF (see run: http://ideone.com/VOE3E0)
4) TDM GCC 32 bit: ELSE IF
5) MSVS 2010: ELSE IF but compiles with warning
Warning 1 warning C4305: 'initializing' : truncation from 'double' to 'float'
What is exactly happening here? What's wrong with the program? Is it implementation defined behavior occurring?
Please help me.
A floating point number maybe represented in the following form:
So there will be rounding or relative errors when the space is less in memory.
From wiki:
The IEEE 754 standard specifies a binary32 as having:
Larger (more bits) floating point representations allow for greater precision.
Floating point math is not exact. Simple values like 0.1 cannot be precisely represented using binary floating point numbers, and the limited precision of floating point numbers means that slight changes in the order of operations can change the result. A must read:
What Every Computer Scientist Should Know About Floating-Point Arithmetic