user6359267
user6359267

Reputation:

Why only multiple "%" is accepted by printf?

Following program give the output %%. Why?

#include <stdio.h>

int main() {
    //code
    printf("%%%%");
    return 0;
}

output:

%%

Upvotes: 2

Views: 53

Answers (2)

Omar
Omar

Reputation: 973

Printf function's first argument is a format represented by a char*, it's not a string.

That's why for printing an int,for example, you have to write "%d". So % is a special character, if you only write % as format, the compiler won't be happy because it is waiting for something after the % (either d, p, x, s, f, ...).

However, by writing %% it means "Print me one escaped %". That's why %%%% prints %%

EDIT: If you want a function that prints exactly what you give, you can use write:

char* mystr = "%%%%";
write(STDOUT_FILENO, mystr, strlen(mystr));

Upvotes: 0

Sourav Ghosh
Sourav Ghosh

Reputation: 134336

TL;DR a % is a valid conversion specifier for printf().

Quoting C11, chapter §7.21.6.1, for conversion specifiers,

Each conversion specification is introduced by the character %. After the %, the following appear in sequence:

.....

— A conversion specifier character that specifies the type of conversion to be applied.

and, from paragraph 8, for % as a conversion specifier character

for % conversion specifier

% A % character is written. No argument is converted. The complete conversion specification shall be %%.

Your code has a pair of %%s.

Upvotes: 3

Related Questions