Example
The following example declares two functions, myFormatText1()
and myFormatText2()
, that
provide format strings to printf()
.
The first function, myFormatText1()
, does
not specify the format_arg
attribute. The compiler does not
check the types of the printf
arguments for consistency
with the format string.
The second function, myFormatText2()
,
specifies the format_arg
attribute. In the subsequent calls
to printf()
, the compiler checks that the types of the
supplied arguments a
and b
are consistent with the format string argument to myFormatText2()
. The compiler produces a warning when a float
is provided where an int
is expected.
#include <stdio.h>
// Function used by printf. No format type checking.
extern char *myFormatText1 (const char *);
// Function used by printf. Format type checking on argument 1.
extern char *myFormatText2 (const char *) __attribute__((format_arg(1)));
int main(void) {
int a;
float b;
a = 5;
b = 9.099999;
printf(myFormatText1("Here is an integer: %d\n"), a); // No type checking. Types match anyway.
printf(myFormatText1("Here is an integer: %d\n"), b); // No type checking. Type mismatch, but no warning
printf(myFormatText2("Here is an integer: %d\n"), a); // Type checking. Types match.
printf(myFormatText2("Here is an integer: %d\n"), b); // Type checking. Type mismatch results in warning
}
$ armclang --target=aarch64-arm-none-eabi -mcpu=cortex-a53 -c format_arg_test.c
format_arg_test.c:21:53: warning: format specifies type 'int' but the argument has type 'float' [-Wformat]
printf(myFormatText2("Here is an integer: %d\n"), b); // Type checking. Type mismatch results in warning
~~ ^
%f
1 warning generated.