in Programming
400 views
1 vote
1 vote
#include<stdio.h>
   int main(){
           int test=0;
         float a = 3424.34;
           printf("hello \n %d",(test? a: 3));
		   return 0;
   }

It is giving output as hello 0 ,I am unable to understand the logic for this so plz clarify this .

in Programming
400 views

2 Comments

since ,the type of a is float and type of 3 is int in that expression so,the expression is converted into float type.why it is n't converted into int type ??
0
0
0
0

1 Answer

4 votes
4 votes
Best answer
In ternary operator of type (x ? y : z), type of expression is type of y and z. If y and z don't have common type, then one is converted to other (according to standard conversion rules) to make type same.

Now in your question, type of a is float, and type of 3 is int, so 3 is converted to float i.e. to 3.0, but you are printing a float value with %d format specifier, which is undefined behavior, and hence the garbage value. Try %f instead if %d, it will print correct value.
selected by

3 Comments

@happy sir

Is there any rule for the type conversion..i.e. whose data type shd be given to whom among the parameters?
0
0
Thanks..that wz rely helpful.
0
0

Related questions