While compiling the following code:
#include <stdio.h>
int main() {
printf("99% Invisible");
return 0;
}
in gcc 7.5.0 I get the following warnings:
test.c: In function ‘main’:
test.c:4:16: warning: ' ' flag used with ‘%n’ gnu_printf format [-Wformat=]
printf("99% Invisible");
^
test.c:4:16: warning: 'I' flag used with ‘%n’ gnu_printf format [-Wformat=]
test.c:4:16: warning: format ‘%n’ expects a matching ‘int *’ argument [-Wformat=]
printf("99% Invisible");
~~~^
What is going on here? I don't see mention of a " " flag or an "I" flag anywhere in documentation. The code outputs 99visible
, essentially ignoring the space and I in the format string and following the %n format.
edit: People seem to be misunderstanding the question. I know how to printf a literal %, and what %n
do. I am just curious what is happening here.
(also, for those who know the context: I know the system in question didn't use C, I am just curious as to what printf is doing here).
CodePudding user response:
The I
flag is a GNU extension to printf
. From the man page:
glibc 2.2 adds one further flag character.
I
For decimal integer conversion (
i
,d
,u
) the output uses the locale's alternative output digits, if any. For example, since glibc 2.2.3 this will give Arabic-Indic digits in the Persian ("fa_IR") locale.
So when the compiler checks the format string, it sees % In
as a format specifier, i.e. the space and I
flags applied to the n
conversion specifier. Since neither flag is applicable to the n
conversion specifier, the compiler emits a warning for each.
CodePudding user response:
To print the literal %
, you must write %%
.
https://en.cppreference.com/w/c/io/fprintf
I
flag is not in the C standard.
CodePudding user response:
It appears that with your compiler when a %
character is encountered in a printf
format string, it scans forward to find a valid format specifier, then interprets everything in-between as a modifier. If those are not valid modifiers, an error is flagged.
As others have pointed out, replace "99% Invisible"
with "99%% Invisible"
to fix the problem.