Why don\'t ANSI C compilers flag the use of a string literal argument in a function call in which the correponding parameter does not have a const qualifier? For example,
gcc: Use the flag -Wwrite-strings
PS. gcc manual explains why this isn't part of -Wall. Anyway, as always, you should find a combination of -W flags that suits your particular needs and coding style. For example, in a recent project I have used something like this: -Werror -Wall -Wextra -Wformat=2 -Winit-self -Wswitch-enum -Wstrict-aliasing=2 -Wundef -Wshadow -Wpointer-arith -Wbad-function-cast -Wcast-qual -Wcast-align -Wwrite-strings -Wstrict-prototypes -Wold-style-definition -Wmissing-prototypes -Wmissing-declarations -Wredundant-decls -Wnested-externs -Winline -Wdisabled-optimization -Wunused-macros -Wno-unused
It is a K&R legacy. Fixing it would break a million programs.
The GNU compiler (and the Intel C compiler as well, iirc) will emit a warning, if -Wwrite-string
is used:
$ gcc -Wall -Wwrite-strings -o foo /tmp/foo.c
/tmp/foo.c: In function 'main':
/tmp/foo.c:12: warning: passing argument 1 of 'somefunc' discards qualifiers from pointer target type
/tmp/foo.c:3: note: expected 'char *' but argument is of type 'const char *'
Concerning VS2010, I can't help you.
What Hans Passant said. const was added as part of the ANSI standard on 1989, so anything from before that didn't have const.
string literals are not const in C; in C++ they are.
edit: to clear up any confusion about my comment, I am referring to the type, not the ability to actually change them.