Home > OS >  Undefined behavior of printf in C?
Undefined behavior of printf in C?

Time:02-10

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".

CodePudding user response:

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("%%");

CodePudding user response:

% is used to signal that you want to print a variable e.g.

int i = 10;
printf("%d", i); //prints 10

In order to just print the '%' sign you must escape it as

printf("%%");

  • Related