#include <stdio.h>
int main() {
float a = 1234.5f;
printf("%d\n", a);
return 0;
}
It displays a 0!! How is that possible? What is the reasoning?
I have deliberately put a %d in the printf statement to study the behaviour of printf.
That’s because
%dexpects anintbut you’ve provided a float.Use
%e/%f/%gto print the float.On why 0 is printed: The floating point number is converted to
doublebefore sending toprintf. The number 1234.5 in double representation in little endian isA
%dconsumes a 32-bit integer, so a zero is printed. (As a test, you couldprintf("%d, %d\n", 1234.5f);You could get on output0, 1083394560.)As for why the
floatis converted todouble, as the prototype of printf isint printf(const char*, ...), from 6.5.2.2/7,and from 6.5.2.2/6,
(Thanks Alok for finding this out.)