prev up next   top/contents search

comp.lang.c FAQ list · Question 12.6

Q: How can I print a '%' character in a printf format string? I tried \%, but it didn't work.


A: Simply double the percent sign: %% .

The reason it's tricky to print % signs with printf is that % is essentially printf's escape character. Whenever printf sees a %, it expects it to be followed by a character telling it what to do next. The two-character sequence %% is defined to print a single %.

To understand why \% can't work, remember that the backslash \ is the compiler's escape character, and controls how the compiler interprets source code characters at compile time. In this case, however, we want to control how printf interprets its format string at run-time. As far as the compiler is concerned, the escape sequence \% is undefined, and probably results in a single % character. It would be unlikely for both the \ and the % to make it through to printf, even if printf were prepared to treat the \ specially.

Additional links: further reading

See also questions 8.8 and 19.17.

References: K&R1 Sec. 7.3 p. 147
K&R2 Sec. 7.2 p. 154
ISO Sec. 7.9.6.1


prev up next   contents search
about this FAQ list   about eskimo   search   feedback   copyright

Hosted by Eskimo North