Reputation: 876
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?
Upvotes: 6
Views: 117
Reputation: 110098
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.
Upvotes: 4