Here is my program:
#include <stdio.h>
int main()
{
int a=0x09;
int b=0x10;
unsigned long long c=0x123456;
printf("%x %llx\n",a,b,c);//in "%llx", l is lowercase of 'L', not digit 1
return 0;
}
the output was:
9 12345600000010
I want to know:
- how function printf() is executed?
- what will happen if the number of arguments isn’t equal to that of formats?
please help me and use this program as an example to make an explanation.
The problem is that your types don’t match. This is undefined behavior.
Your second argument
bdoes not match the type of the format. So what’s happening is thatprintf()is reading past the 4 bytes holding b (printfis expecting an 8-byte operand, butbis only 4 bytes). Therefore you’re getting junk. The 3rd argument isn’t printed at all since yourprintf()only has 2 format codes.Since the arguments are usually passed consecutively (and adjacent) in memory, the 4 extra bytes that
printf()is reading are actually the lower 4 bytes ofc.So in the end, the second number that’s being printed is equal to
b + ((c & 0xffffffff) << 32).But I want to reiterate: this behavior is undefined. It’s just that most systems today behave like this.