Question

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:

  1. how function printf() is executed?
  2. 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.

Was it helpful?

Solution

The problem is that your types don't match. This is undefined behavior.

Your second argument b does not match the type of the format. So what's happening is that printf() is reading past the 4 bytes holding b (printf is expecting an 8-byte operand, but b is only 4 bytes). Therefore you're getting junk. The 3rd argument isn't printed at all since your printf() 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 of c.

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.

OTHER TIPS

If the arguments that you pass to printf don't match the format specification then you get undefined behavior. This means that anything can happen and you cannot reason about the results that you happen to see on your specific system.

In your case, %llx requires and argument of type unsigned long long but you supplied an int. This alone causes undefined behaviour.

It is not an error to pass more arguments to printf than there are format specificiers, the excess arguments are evaluated but ignored.

printf() increases a pointer to read an argument at a time according to the format. If the number of formatting arguments is larger than the number of parameters, then printf() will output data from unknown memory locations. But if the number of parameters is larger than the number of formatting arguments, then no harm was done. E.g. gcc will warn you if the number of formatting arguments and parameters don't match.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top