下一行
char *s = "string";
即使使用 -Wall
也不会在 gcc
上抛出任何警告/错误。
AFAIK,指针 s
直接指向 .rodata
的某个部分,使其成为指向 const
char
.
那么,为什么指针不提示并期待:
const char *s = "string";
加:不管怎样,使用后者是更好的做法吗?
最佳答案
来自 gcc 编译选项:
-Wwrite-strings When compiling C, give string constants the type const char[length] so that copying the address of one into a non-const char * pointer produces a warning. These warnings help you find at compile time code that can try to write into a string constant, but only if you have been very careful about using const in declarations and prototypes. Otherwise, it is just a nuisance. This is why we did not make -Wall request these warnings.
所以显然您需要明确允许 -Wwrite-strings,而 Wall 不包含它。
关于c - 为什么 char *s = "string"在不是 const 时不显示错误或警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28276346/