The most likely reason printf does not interpret the bits in i , since the floating point number is because printf does not see i at all. I suspect that you are using x86_64 or a similar platform where arguments are passed to functions in registers. Usually printf interprets your int as any format specifier that you gave it. But floating point arguments for functions are handled differently on x86_64 and placed in different registers. So the reason you get 0 as the output is because printf extracts the first floating point argument after the format string instead of the first general-purpose register and prints this. Since you did not use floating point registers before your call to printf , they are most likely reset to zero from running the program.
Here you can try:
#include <stdio.h> int main(int argc, char **argv) { printf("%f\n", 17.42); printf("%f\n", 0x87654321); return 0; }
I get this output:
$ ./foo 17.420000 17.420000
Having said all this, the only correct answer: this is undefined behavior, do not do this. But itβs interesting to see what happens under the hood.
If you want to dive into this and work on Linux / MacOS / * BSD this document, section 3.2.3 describes how arguments (including varargs functions like printf) are described. Windows does things a little differently, but in this case the result on Windows will be exactly the same. printf on Linux / MacOS / * BSD expects the argument to be printed to %xmm0 ( %xmm1 on Windows), while your call passes it to %rsi ( %rdx on Windows).
Of course, if I'm wrong about x86_64, ignore everything I said and look at the answer from @SirDarius, because this applies to many (especially old) architectures. If you use alpha, sparc, powerpc, arm, etc., you are on your own. Call printf once with int, once with a float, parse the compiled code and see how the arguments are passed.
Art Dec 18 '14 at 10:05 2014-12-18 10:05
source share