How can printf issue a compiler warning?

I was wondering how a function can trigger a compilation warning?

This occurred to me because when we supply the wrong format specifier in the first argument of printf (scanf) for the variable that maps to this type specifier and compile with gcc with the -Wall parameter, the compiler generates a warning.

Now printf and scanf regularly implement variational functions, as I understand it, and I don’t know how to check the value of a string at compile time, not to mention giving a warning if something does not match.

Can someone explain to me how I get a compiler warning?

+8
c gcc printf scanf
source share
2 answers

Warnings are implementations (i.e., compiler and standard HTML standard library ). You may have a compiler giving very few warnings (look tinycc ...) or not even ...

I am focusing on recent GCC (e.g. 4.9 or 5.2 ...) on Linux.

You receive such warnings because printf declared with the corresponding __attribute__ (see GCC function attributes )

(With GCC, you can also declare your own printf functions with the format attribute ..)

BTW, the standard compatible compiler can specifically implement the <stdio.h> header. Thus, it could handle #include <stdio.h> without reading any header file, but by changing its internal state.

And you can even add your own function attributes, for example. by setting up your GCC using MELT

+6
source share

How can printf issue a compiler warning?

Some compilers parse the format and other arguments like printf() and scanf() at compile time.

 printf("%ld", 123); // type mis-match `long` vs. `int` int x; printf("%ld", &x); // type mis-match 'long *` vs. `int *` 

However, if the format is computed, then this check is not performed because it is a run-time problem.

 const char *format = foo(); printf(format, 123); // mis-match? unknowable. 
+3
source share

All Articles