I was looking at two C programs, These codes are giving different outputs but i was thinking of getting the same output, I have already asked same question other c developer forum, But I am not satisfied from that answers, can you please explain why they are giving such outputs.
enter code here Code 1
#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 output of the above program is ELSE IF
Code 2
include<stdio.h>
int main()
{
float x = 0.5;
if (x == 0.5)
printf(“IF”);
else if (x == 0.5f)
printf(“ELSE IF”);
else
printf(“ELSE”);
}
#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 output of above program is “ELSE IF” which means the expression “x == 0.1″ returns false and expression “x == 0.1f” returns true.
Let consider the of following program to understand the reason behind the above output.
#include<stdio.h>
int main()
{
float x = 0.1;
printf("%d %d %d", sizeof(x), sizeof(0.1), sizeof(0.1f));
return 0;
}
The output of above program is “4 8 4” on a typical C compiler. It actually prints size of float, size of double and size of float.
The simple answer is that 0.1 is not exactly represent-able within the precision of float and has to be truncated to the precision of float when assigned. For the comparison, the float is converted to double and compared with the literal 0.1 which was truncated to the precision of double.
If you change to double you will get True, as both will be truncated to the same value.
If you change to a number represent-able within the mantissa bits of the float (0.5 or 0.25 or 0.75 etc) you will also get True.