How does this program work?
c, c++, endianness, memory, printf
Solution
That's because `%d` expects an `int` but you've provided a float.
Use `%e`/`%f`/`%g` to print the float.
On why 0 is printed: The floating point number is converted to `double` before sending to `printf`. The number 1234.5 in double representation in little endian is
00 00 00 00 00 4A 93 40
A `%d` consumes a 32-bit integer, so a zero is printed. (As a test, you could `printf("%d, %d\n", 1234.5f);` You could get on output `0, 1083394560`.)
As for why the `float` is converted to `double`, as the prototype of printf is `int printf(const char*, ...)`, from 6.5.2.2/7,
The ellipsis notation in a function prototype declarator causes argument type conversion to stop after the last declared parameter. The default argument promotions are performed on trailing arguments.
and from 6.5.2.2/6,
If the expression that denotes the called function has a type that does not include a prototype, the integer promotions are performed on each argument, and arguments that have type `float` are promoted to `double`. These are called the default argument promotions.
(Thanks Alok for finding this out.)
Problem
``` #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`.