C program output?

printf("%%d",12) prints %dd whereas
printf("%%%d",12) prints %12d

what is the reason behind this? how does it actually work?

When printf encounters % it thinks as a format specifier unless it encounters another %.
%% is used to print %

When you do printf("%%d",12) -

  1. When the compiler encounters first %, it recognizes it as a format specifier.
  2. When it encounters the second %, the second % behaves as a escape character for the first % (remember % is escaped with another %)
  3. So now you have a single ā€œ%ā€ and then d, ie, ā€œ%dā€ (with ā€œ%ā€ not being a format specifier here).
  4. Since you have specified a parameter 12 to printf and printf is not expecting any parameter (since there is no format specifier, it gives a warning that there are extra arguments) it ignores 12 and prints ā€œ%dā€.

Now if you had %%%d, the compiler would interpret the first two % as a single ā€œ%ā€ and then you have this followed by %d, which will compile to ā€œ12ā€. So the output will be ā€œ%12ā€.

Ideone - http://ideone.com/aYOIZZ

1 Like