I wrote this intentionally wrong code
printf("%d %d", 1);
compiling with g++
and -Werror=format
.
The compiler gives this very impressive warning:
error: format '%d' expects a matching 'int' argument [-Werror=format]
As far as I can see, there's no way the compiler can tell that the code is wrong, because the format string isn't parsed until runtime.
My question: does the compiler have a special feature that kicks in for printf and similar libc functions, or is this a feature I could use for my own functions? String literals?
As long as the format string is a string literal, it can be parsed at compile time. If it isn't (which is usually a bad idea anyway), then you can get a warning about that from
-Wformat-security
.Yes.
Yes, as long as you're using the same style of format string as
printf
(or various other standard functions likescanf
orstrftime
).to indicate that the second argument is a
printf
-style format string, and the values to format begin with the fourth. See http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html.