Using %f to print an integer variable

Prateek picture Prateek · Jul 26, 2012 · Viewed 9.2k times · Source

The output of the following c program is: 0.000000

Is there a logic behind the output or is the answer compiler dependent or I am just getting a garbage value?

#include<stdio.h>

int main()
{
    int x=10;
    printf("%f", x);
    return 0;
}

PS:- I know that to try to print an integer value using %f is stupid. I am just asking this from a theoretical point of view.

Answer

chris picture chris · Jul 26, 2012

From the latest C11 draft:

§7.16.1.1/2

...if type is not compatible with the type of the actual next argument 
(as promoted according to the default argument promotions), the behavior 
is undefined, except for the following cases:

— one type is a signed integer type, the other type is the corresponding 
unsigned integer type, and the value is representable in both types;
— one type is pointer to void and the other is a pointer to a character type.