644 views
1 votes
1 votes
#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 .

1 Answer

Best answer
4 votes
4 votes
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

Related questions

0 votes
0 votes
1 answer
1
0 votes
0 votes
1 answer
2
radha gogia asked Aug 10, 2015
392 views
CASE A: CASE A: &#8234;#&lrm;include&#8236;<stdio.h int divide( int a, b) { return 7; } int main() { int a=divide(8,3); printf("%d",a); return 0; }CASE B :CASE B : #inclu...
0 votes
0 votes
1 answer
4
radha gogia asked Jul 28, 2015
958 views
int * p(void) { int *x; *x=10; return (x); } We create *x, and dereference it before assigning anything to it (x). Most likely, when we are declaring something on the sta...