Why doesn't this program print the %
sign?
#include <stdio.h> main() { printf("%"); getch(); }
Your problem is that you have to change:
printf("%");
to
printf("%%");
Or you could use ASCII code and write:
printf("%c", 37);
:)
There's no explanation in this topic why to print a percentage sign. One must type %%
and not for example an escape character with percentage - \%
.
From comp.lang.c FAQ list · Question 12.6:
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.
So the reason why one must type printf("%%");
to print a single %
is that's what is defined in the printf function. %
is an escape character of printf's, and \
of the compiler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With