#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;
}
Output
$ ./a.out
4 4 8 8
As per above code, we can see sizeof(0.1)
and sizeof(0.1f)
are not same.
sizeof(0.1) is 8 bytes
, while sizeof(0.1f) is 4 bytes
.
but while assigning the value to float variable f
, it automatically truncates its size to 4 bytes
.
While in below code, while comparing it with float x it is not truncating and 4 bytes of float
are compared with 8 bytes of 0.1
, value of float x
matches with 0.1f
as both are of 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");
}
Output
$ ./a.out
ELSE IF
why and how it is truncating while assigning and not while comparing?