Question

The following code gives me the output as 'd':

void main()
{

  short int a=5;

   printf("%d"+1,a);

   getch();

}

How does printf() actually work?

Was it helpful?

Solution

printf does not "see" the format specifier because you are passing a pointer to "%d" plus one. This is equivalent to passing "d" by itself:

printf("d", a);

will print d and ignore a. This is not specific to printf, pointer arithmetic works like that with all char pointers, including pointers obtained from string literals (i.e. double-quoted sequences of characters).

OTHER TIPS

here is the problem printf("%d"+1,a); it wont display because there is only one format specifier and this ("%d"+1) generate error

it can be either printf("%d+1",a); or printf("%d",a+1);

String literals such as "%d" are array expressions, and in most contexts an array expression will be converted to a pointer expression whose value is the address of the first element of the array:

Item        Address        00   01   02   03
-----       -------        --   --   --   --
"%d"        0xfffbec00     '%'  'd'   0   ??

The string literal "%d" starts at address 0xfffbec00 (for example). By writing "%d"+1, you're adding 1 to the resulting pointer value (giving 0xfffbec01), so you're effectively passing the string literal "d" to printf.

Since the string "d" does not contain a format specifier, printf prints the string as-is. The argument a is evaluated before being passed to printf, but is otherwise ignored.

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