I just ran into this weird scenario and I just cant explain it. I'm just really curious as to whats happening more than anything. I have this sample code:
#include <stdio.h>
#include <stdint.h>
int main()
{
int64_t qty = 900;
double p = 74.45;
printf( "%f|%ld\n", p, qty );
printf( "%f|%ld\n", qty, p );
return 0;
}
Note that in the second printf I provide the arguments in the WRONG ORDER, not to mention the fact that the types are wrong. However, I still get the CORRECT output in both? How odd is that... Compiling with gcc 7.2:
$ ./a.out
74.450000|900
74.450000|900
Whats going on here?
Printf is not the thing being buffered, it's stdio, so all similar functions will behave in the same way. To demonstrate the buffering, all you have to do is printf a lot of characters, usually more than 1024, and printf will print as you will have exceeded the maximum buffer length and it will automatically fflush.
In C printf(), %n is a special format specifier which instead of printing something causes printf() to load the variable pointed by the corresponding argument with a value equal to the number of characters that have been printed by printf() before the occurrence of %n.
3 means "use at least 3 spaces to display, padding as needed" d means "The variable will be an integer"
Passing the wrong argument types to printf
causes undefined behavior. When you have undefined behavior, anything can happen, including seemingly "correct" behavior.
In this case, it's most likely that on this architecture integer and floating-point values are passed to variable-argument functions in different registers. So printf
prints the first floating-point register for %f
and the first integer register for %ld
, which ends up being correct no matter the order that they were passed in.
However, this should never be relied on, and may even give the wrong results on this specific architecture depending on the compiler, optimizations, etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With