for example by adding \" it interprates " as a string then why cannot we use \ in our case?
Because escape characters are interpreted at the compiler level and format specifiers are interpreted at the library level. If \%
gave you a literal '%'
then it would still be treated as the opening character for a format specifier by the library code. Further, even though the library could be specified to use \%
, it would have to actually look like this in user code:
printf("How are you \\%dad\\%");
And the reason is because the compiler will try to interpret any escape, so you need to escape the escape opening character to get a literal '\'
. In other words, it's awkward either way, so printf()'s designer took the wiser route, in my opinion, and simply made a format specifier for a literal '%'
.
It's probably a little advanced, but you can see a working implementation of printf() here:
http://code.google.com/p/c-standard-library/source/browse/src/internal/_printf.c#35
And the format specifier parsing is done in this function:
http://code.google.com/p/c-standard-library/source/browse/src/internal/_fmtspec.c#128