When I ran the following code:

printf("%d %f %d %d %f\n", 1.2 , 3000, 2.5, 400, 500);

What I thought was the answer might be some meaningless number, but the result was actually:

3000 1.200000 400 500 2.500000

which is just the same number and in the same format as my input.

It was so meaningful that I can't persuade myself ignoring it.

Could someone tell me the reason? I would be very grateful.

p.s. I'm using Clion as my IDE.

2

There are 2 best solutions below

1
On BEST ANSWER

Just a guess: On your ABI floating point arguments are passed via the FPU stack, integers through the CPU-stack. So when printf pulls the arguments, it pulls %fs from the FPU stack and pops %ds off the CPU-stack. If I am right, printf("%d %d %d ***** %f %f\n", 1.2 , 2.5, 3000, 400, 500); should work for you too. So the mixup between floats and others (%d, %s & Co) will be recovered for you, the order is preserved. Needless to add: all this is >150% UB.

0
On

Supplying inappropriate type for a given format specifier is undefined behavior, you can never "justify" the result. It may seem to work fine, but you never know, internally it may be transferring all your money to some other account!!

Quoting C11, chapter §7.21.6.1, P9

[...] If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

In your case,

  • %d expects int, you supplied double (literal 1.2 is a double)
  • %f expects a double, you supplied an int.

So, you cause UB. Just don't do it.