String literals vs const char* in C

前端 未结 5 1636
傲寒
傲寒 2020-12-09 20:25

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,

相关标签:
5条回答
  • 2020-12-09 20:41

    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

    0 讨论(0)
  • 2020-12-09 20:42

    It is a K&R legacy. Fixing it would break a million programs.

    0 讨论(0)
  • 2020-12-09 20:42

    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.

    0 讨论(0)
  • 2020-12-09 20:43

    What Hans Passant said. const was added as part of the ANSI standard on 1989, so anything from before that didn't have const.

    0 讨论(0)
  • 2020-12-09 20:51

    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.

    0 讨论(0)
提交回复
热议问题