How does implicit type conversion happens in the following c snippet?What will be the output?
#include<stdio.h>
void main()
{
float f = (1/2)+(1.0/2)+(1.0/2.0);
double d = 1/2;
printf("%f \n %d",f,d);
}
How does implicit type conversion happens in the following c snippet?What will be the output?
#include<stdio.h>
void main()
{
float f = (1/2)+(1.0/2)+(1.0/2.0);
double d = 1/2;
printf("%f \n %d",f,d);
}
1/2 is an integer divided by an integer resulting in an integer value i.e, 0(.5 is truncated )
1.0/2 is an integer divided by a double value . So 2(the integer value) is promoted to a double type and then division occurs giving a double value. So the resulting value is 0.5.
1.0/2.0 results in division of a double by another double and the result is simply 0.5 in double type.
Finally all these are added to get 1.0 which is of double type. It is then casted to float type as f is a float type variable.
Moreover printing a double type value with %d specifier results in undefined behaviour.See this post