#include<stdio.h>
int main()
{
float f = 0.1;
double d = 0.1;
printf("%lu %lu %lu %lu\n", sizeof(f), sizeof(0.1f), sizeof(0.1), sizeof(d));
return 0;
}
Exit
$ ./a.out
4 4 8 8
As in the previous code, we can see that sizeof(0.1)they sizeof(0.1f)do not match.
sizeof(0.1) is 8 bytes, a sizeof(0.1f) is 4 bytes. but when assigned, value to float variable fit automatically trims its size to 4 bytes.
While in the code below when comparing with float x it is not cropped and 4 bytes of floatcompared with 8 bytes of 0.1, the value is the float xsame 0.1fas since both have 4 bytes.
#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");
}
Exit
$ ./a.out
ELSE IF
why and how does it truncate when assigned, and not when compared?
source
share