Repeat this for yourself for two weeks once a night before bedtime:
printf is not typical. printf is not typical. printf is not typical.
A function will only work if you pass it an argument of the type that you promise. Everything else is undefined behavior. You promise double (via %f ), but specify int (literal type 7 ), so this behavior is undefined. Shame on you.
(I did go into details once to explain the actual conclusion, if you're interested.)
Update. Since you are interested in explaining this specific behavior, here is the (relevant) assembly for this code on my x86 / GCC4.6.2 / -O3:
First data sections:
.LC0: .long 1921946325 .long 1076013872 // 0x 4022AB30 728E92D5 is the binary rep of 9.334354 .LC1: .string "%.2f\n" .LC2: .string "%.5f\n" .LC3: .string "%03d\n"
Now the code:
fldl .LC0 // load number into fp register fstpl 4(%esp) // put 64-bit double on the stack movl $.LC1, (%esp) // first argument (format string) call printf // call printf movl $7, 4(%esp) // put integer VA (7) onto stack movl $.LC2, (%esp) // first argument (format string) call printf // call printf movl $9, 4(%esp) // put integer VA (9) onto stack movl $.LC3, (%esp) // first argument (format string) call printf // call printf
The reason you see what you see now is simple. Let it momentarily switch to the full 17-digit output:
printf("%.17f\n", 9.334354); printf("%.17f\n", 7);
We get:
9.33435399999999937 9.33435058593751243
Now replace the integer with the βcorrectβ binary component:
printf("%.17f\n", 9.334354); printf("%.17f\n", 1921946325);
And voila:
9.33435399999999937 9.33435399999999937
It happens that double occupies 8 bytes on the stack, the value is 0x4022AB30728E92D5 . An integer takes only 4 bytes, and as it happens, the least significant four bytes are overwritten, so the floating point value is still almost the same. If you overwrite four bytes with the same bytes as in the original float, you will get the exact result.
I could add that it is just luck that the most significant four bytes remain untouched. In different circumstances, they could be rewritten by something else. In short, "undefined behavior".