Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can printf issue a compiler warning?

Tags:

c

gcc

printf

scanf

I was wondering how can a function issue a compile-time warning?

This came to my mind because when we supply wrong format specifier in the first argument of printf (scanf) for the variable matched with that type specifier and compile with gcc with -Wall option on, compiler issues a warning.

Now, printf and scanf are regularly implemented variadic functions as I understand and I dont know any way to check the value of the string at the compile-time, let alone issue a warning if something doesnt match.

Can someone explain me how I get compiler warning then?

like image 640
user1635881 Avatar asked Oct 24 '15 18:10

user1635881


2 Answers

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

like image 169
Basile Starynkevitch Avatar answered Oct 26 '22 19:10

Basile Starynkevitch


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.
like image 23
chux - Reinstate Monica Avatar answered Oct 26 '22 20:10

chux - Reinstate Monica