No error message when format string is passed as variable to printf functions family

Martin Sebor msebor@redhat.com
Wed May 13 21:36:00 GMT 2015


> At the end of the day, it all comes down to passing format string as
> variable - the code below also does not produce error:
>
> const char *str = "Last printf: %B\n";
> printf(str, 2);
>
> Can someone explain why this happens?

Because with only a few exceptions (e.g., -Wuninitialized,
-Wstrict-aliasing, or -Wstrict-overflow), warnings are
implemented in an early stage of the translation process
before the compiler has done the sort of program analysis
or optimization necessary to "see" variable values. It only
considers the values of literals and constants, as in:

   const char str[] = "Last printf: %B\n";
   printf (str, 2);   // warning

It doesn't do any sort of indirection so this won't cause
a warning either:

   const char* const str = "Last printf: %B\n";
   printf (str, 2);   // no warning

Martin



More information about the Gcc-help mailing list