Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why printf(char[]) generates a warning, meanwhile printf("asdf") doesn't [duplicate]

Tags:

c

gcc

printf

Possible Duplicate:
warning: format not a string literal and no format arguments

I have very simple question: Why when I make char[] s = "hi"; printf(s) it issues a warning: "warning: format not a string literal and no format arguments", meanwhile printf("aa") doesn't.

I've already read a difference between char array and string literal (one is const char const* and another is char*), but from printf() signature:

http://www.gnu.org/software/libc/manual/html_node/Formatted-Output-Functions.html#Formatted-Output-Functions

I see that it's suitable for any of that types. So my question is why printf("aaa") don't issue any warnings (does it somehow checks that literal is a const, meanwhile array isn't)?

like image 667
dhblah Avatar asked Jul 10 '12 15:07

dhblah


1 Answers

The GNU compiler and a lot of other compilers these days do indeed check the format strings for the printf-family against the arguments supplied. The compiler is warning that it cannot do this for non-literal strings.

Using a non-literal format string is considered to be a bad practice. Using a format string that you do not control is much worse.

like image 183
D.Shawley Avatar answered Nov 15 '22 04:11

D.Shawley