printf specify integer format string for float

#include <stdio.h>

int main()
{
    float a = 5;
    printf("%d", a);
    return 0;
}

This gives the output:

0

Why is the output zero?


Solution 1:

%d format specifier can only be used with values of type int. You are passing a double (which float will be implicitly converted to). The resultant behavior is undefined. There no answer to "why it prints 0?" question. Anything can be printed. In fact, anything can happen.

P.S.

  1. That's int main, not void main.
  2. There's no such header as conio.h in standard C.

Solution 2:

It doesn't print 5 because the compiler does not know to automatically cast to an integer. You need to do (int)a yourself.

That is to say,

#include<stdio.h>
void main()
{
float a=5;
printf("%d",(int)a);
}

correctly outputs 5.

Compare that program with

#include<stdio.h>
void print_int(int x)
{
printf("%d\n", x);
}
void main()
{
float a=5;
print_int(a);
}

where the compiler directly knows to cast the float to an int, due to the declaration of print_int.

Solution 3:

You should either cast it to an int to use %d, or use a format string to display the float with no decimal precision:

int main() {
  float a=5;
  printf("%d",(int)a); // This casts to int, which will make this work
  printf("%.0f",a); // This displays with no decimal precision
}