How can printf issue a compiler warning?

How can printf issue a compiler warning?

Some compilers analyze the format and other arguments type of 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 *`

Yet if the format is computed, then that check does not happen as it is a run-time issue.

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

Warnings are implementation (i.e. compiler & C standard library) specific. You could have a compiler giving very few warnings (look into tinycc...), or even none...

I'm focusing on a recent GCC (e.g. 4.9 or 10...) on Linux.

You are getting such warnings, because printf is declared with the appropriate __attribute__ (see GCC function attributes)

(With GCC you can likewise declare your own printf-like functions with the format attribute...)

BTW, a standard conforming compiler is free to implement very specially the <stdio.h> header. So it could process #include <stdio.h> without reading any header file but by changing its internal state.

And you could even add your own function attributes, e.g. by customizing your GCC with your GCC plugin

Tags:

C

Printf

Gcc

Scanf