April Johnson April Johnson - 1 year ago 49
C Question

Strange behaviour of two successive printf() calls in C

I was playing with C; check this out:

#include <stdio.h>
#include <stdlib.h>

void main() {
printf("%d\n", 1.5);
printf("%f", 0);

I expected the output:


but it prints:


Did the first
pass the
to 2nd

PS: I’m aware of (
for ints,
for floats ). As I mentioned, I was just messing with the code.

PS2: I'm using DevC++ & Code::Blocks.

Answer Source

The behavior is undefined as per the C Standard, here is what may be happening on your system:

  • For the first call printf("%d\n", 1.5); main passes the floating point value 1.5 as a double in the first XMM register and call printf().
  • printf() does not modify the XMM register because if does not perform any floating point operation to handle the format "%d". It retrieves the value to print from a different place: a register or the stack, and this value happens to be 0.
  • for the second call printf("%f", 0);, main does not change the XMM either because it passes an int value of 0 via the other place, a register or the stack.
  • the second printf() finally gets the double value for the format %f from the XMM register where 1.5 has been stored earlier. Hence the output 1.500000.

None of the above is guaranteed in any way, but this is probably the explanation you are interested in. Different systems may handle parameter passing in different ways, they are part of the ABI (Application Binary Interface).

Just for fun, you might want to try this variation:

printf("first %d, second %f\n", 1.5, 42);

which on my system outputs first 42, second 1.500000

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download