@mior.farhan.9 Thankyou for your answer but I had a doubt as to what is the mechanism or how does the compiler interprate that by adding one more % in the string it considers the next %d as part of string and not format specifier..for example by adding \" it interprates " as a string then why cannot we use \ in our case?

Edited 3 Years Ago by saurabh.mehta.33234

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:


And the format specifier parsing is done in this function:


Sorry, couldn't get my CodeBlock IDE to work, so I did it on the ideone.com C compiler.

It'll obviously work, but it's kind of silly. printf() offers a better way to do it, and if you're just printing a string with no replacements then puts() or fputs() would be a better solution anyway:

puts("How are you %dad%");

Sorry, I thought the question was
how to print '% ' in printf()

That was the question, but if you're going to take it to unreasonable extremes, it's important to bring a little sanity to the thread. ;)

I reccommend nullptr's suggestion. You're going to have to get used to the double percent sign anyway, because there are some situations where you need to have both a format specifier and a percent sign in the same call to printf().

printf("Jimmy got a %d%% on his quiz!", percentage);

Using the the "%%" in the format string is the only good solution as far as I'm concerned. The function itself states that this should be used to print a single '%' symbol; it makes no sense to create all sorts of more complex constructs to do something that can be done in a simple manner.

This article has been dead for over six months. Start a new discussion instead.