0

I have tried escaping it using a backslash.

#include <stdio.h>

int main(void) {
    printf("\%");
    return 1;
}

But it doesn't work. What is the correct syntax?

Jimmay
  • 959
  • 3
  • 13
  • 27
  • 2
    `%%`, as you could probably tell by reading the documentation of `printf()`, or at least a beginner C tutorial/book. –  Dec 14 '13 at 17:39

2 Answers2

2

Two percentage signs:

printf("%%");
Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195
  • Thanks. I wonder why it doesn't follow the same pattern as regular escaping though. – Jimmay Dec 14 '13 at 17:40
  • 4
    @Jimmay, because it has nothing to do with escaping. It has to do with how `printf` handles the format specifiers. Escaping is valid for all strings and is done at compile time. The format specifiers (the percentage signs) are only used by some functions and used at run-time. If you would `write` to `stdout`, you do not need to use double percentage signs. – Bart Friederichs Dec 14 '13 at 17:43
  • 1
    [`puts`](http://en.cppreference.com/w/c/io/puts) might be a better example of that: it just prints the given string to `stdout` without any processing done to it. – Kninnug Dec 14 '13 at 17:54
1
 printf("\%");  

will print % if you compile it in C89 mode (in K&R C, it is behavior defined).
In C99/11 this is not valid.

C11: 6.4.4.4 Character constants:

The double-quote " and question-mark ? are representable either by themselves or by the escape sequences \" and \?, respectively, but the single-quote ' and the backslash \ shall be represented, respectively, by the escape sequences \' and \\.

confirms that there is no escape sequence like \%.
The preferred way is

  printf("%%");   

Almost similar question is answered here .

Community
  • 1
  • 1
haccks
  • 104,019
  • 25
  • 176
  • 264
  • I prefer the look of \%, so now I compile as K&R. Thanks. – Jimmay Dec 14 '13 at 18:14
  • Are you sure `printf("\%")` is valid K&R C? The string constant itself is valid and the same as `"%"`, of course, but I am pretty sure, that the call to `printf` is not, because `"%"` is not a valid format specifier (at least in C99, the behavior of using invalid format specifications is undefined (C99 §7.19.6.1(9))). But I don't have the K&R book here to verify that, unfortunately. – mafso Dec 16 '13 at 16:24
  • @haccks Thanks a lot for the link! So, according to your link this is clearly undefined in K&R, and the appendix to this second edition doesn't mention this as a difference to its first edition. – mafso Dec 19 '13 at 19:29