-6

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);

}
  • 2
    Wellcom to SO. Which conversion in particular do you not understand? Did you put any effort in answering this? Where is this from, are you just dumping your homework to us? – Jens Gustedt Aug 29 '15 at 16:38
  • I did my research sir and i found that when 1.an integer variable is assigned to float or double datatype it gets promoted and 2.when float or double datatype is assigned to int or char,value gets truncated.I was unable to analyze scenarios in mixed expression.Thanks – Aravind Sharma Aug 31 '15 at 16:23
  • A question similar to this was asked in AMCAT exam which i was unable to answer. – Aravind Sharma Aug 31 '15 at 16:34

1 Answers1

1

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

Community
  • 1
  • 1
Sourav Kanta
  • 2,727
  • 1
  • 18
  • 29