Search code examples
cstdio

Undefined behavior of printf in C?


What should be the output of a single percent sign?

#include <stdio.h>

void main()
{
    printf("%");
}

"Unknown format code" is not like "Unknown escape sequence".


Solution

  • What you're doing is undefined behavior.

    Section 7.21.6.1p9 of the C standard regarding format specifiers for fprintf (and by extension printf) states:

    If a conversion specification is invalid, the behavior is undefined. If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

    Also, gcc will generate a warning with -Wall if you do this:

    warning: spurious trailing ‘%’ in format [-Wformat=]
    

    The correct way to print a % character is with the format specifier %%.

    printf("%%");