Output of the following program when we use %f to print integer variable

Write the output and explain it.

#include <stdio.h>
#include <string.h>
int main() 
{
    int i, j;
    i = 5;
    j = 102;
    printf("%f  *  %d",i,j);
    return 0;
}

I run the program and I get output: 
0.000000  *  -1218384307
but how, can anyone explain it?

5Comments
Tinu Dahiya @tinudahiya
28 Jan 2016 03:22 am

when you use %f in printf , compiler try to get the int value for i and j, %f is for float datsy it prints the i = 0.

as u earlier write %f, compiler  implicitly convert the next int value into float and print the garbage value.

meet @meet
28 Jan 2016 05:30 am

but i write %d for j, and j is integer then how compiler print the garbage value ??? i do not understood

Tinu Dahiya @tinudahiya
28 Jan 2016 06:35 pm

compiler implicitly change  that int to float.

try this below code :

// you get the garbage value
int main() 
{
    int i, j;
    i = 5;
    j = 102;
 int sum = i +j;
   printf("%f",sum);
    return 0;
}
int main() 
{
    int i, j;
    i = 5;
    j = 102;
    float sum = i+j;
    printf("%f",sum); //you get sum = 7
    return 0;
}

 

Gagan Batra @gaganbatra
12 Mar 2016 12:11 am

For second main method, answer is 107.000000 and not 7. You can verify it.

Gagan Batra @gaganbatra
12 Mar 2016 01:42 am
  • First, when we use %f in printf for integer variable, compiler doesn't find any float variable(as i is integer) so it returns 0.000000 (0 in float). To get 5.000000, you need to store it in a float variable first and then print it.
  • Similar is the case when we use %d in printf for float variable, compiler will not find any integer variable and will return 0 (For better understanding, try taking i as float and then use %d to print the value of i).
  • Second, value of j comes out to be different on different OS as C is OS dependent. I tried it in Windows using GCC, it returned garbage value but when tried on MAC OS using GCC, it gave interesting outputs. Following code snippet is executed on MAC. 
#include<stdio.h>
int main()
{
int i,j;
i=5;
j=102;
printf("%f * %d\n",i,j);
printf("%d * %f\n",i,j);
printf("%d * %f * %d\n",i,j);
printf("%f * %f * %d\n",i,j);
printf("%f * %f * %f\n",i,j);
return 0;
}

output
0.000000 * 5
5 * 0.000000
5 * 0.000000 * 102
0.000000 * 0.000000 * 102
0.000000 * 0.000000 * 0.000000

 

Pages