43

Why doesn't this program print the % sign?

#include <stdio.h>

main()
{
     printf("%");
     getch();
}
Dada
  • 6,313
  • 7
  • 24
  • 43
Paul Filch
  • 867
  • 2
  • 7
  • 13
  • 3
    So did you read the documentation? What did it say about the percent sign? –  Jul 21 '13 at 17:20
  • This question can be easily answered through Google. The OP could have used his logic, ie (`'//`) is the character constant for `/` and applied this. Isn't there also a man page on `printf`? – TheBlueCat Jul 21 '13 at 20:38
  • 1
    Perhaps you meant to say that `'\\'` is the character constant for `\ `? The character constant for `/` is `'/'`. – This isn't my real name Jul 22 '13 at 18:57

4 Answers4

94

Your problem is that you have to change:

printf("%"); 

to

printf("%%");

Or you could use ASCII code and write:

printf("%c", 37);

:)

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
C_Intermediate_Learner
  • 1,800
  • 3
  • 18
  • 22
27

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
macfij
  • 3,093
  • 1
  • 19
  • 24
8

Use "%%". The man page describes this requirement:

% A '%' is written. No argument is converted. The complete conversion specification is '%%'.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469
3

Try printing out this way

printf("%%");
Santhosh Pai
  • 2,535
  • 8
  • 28
  • 49
  • 4
    This answer could be more useful than that. It doesn't give any reference enabling the readers to learn about their mistakes. – Diti Mar 22 '14 at 16:54