#include <stdio.h>
int main(void){
float a = 1.1;
double b = 1.1;
if(a == b){
printf("if block");
}
else{
printf("else block");
}
return 0;
}
Prints: else block
#include <stdio.h>
int main(void){
float a = 1.5;
double b = 1.5;
if(a == b){
printf("if block");
}
else{
printf("else block");
}
return 0;
}
Prints: if block
What is the logic behind this?
Compiler used: gcc-4.3.4
This is because
1.1is not exactly representable in binary floating-point. But1.5is.As a result, the
floatanddoublerepresentations will hold slightly different values of1.1.Here is exactly the difference when written out as binary floating-point:
Thus, when you compare them (and the
floatversion gets promoted), they will not be equal.