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
//