为什么 char *s = "string" 在不是 const 时不显示错误或警告
Why char *s = "string" shows no error or warning when it is not const
下面一行
char *s = "string";
不会在 gcc
上抛出任何 warning/error 即使 -Wall
。
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 不包括它。
理想情况下,任何修改字符串文字内容的尝试都是未定义行为。因此,始终鼓励在声明字符串文字时使用 const
。
const char *s = "string";
而不是,
char *s = "string";
事实上,在 C++
中不推荐在没有 const
的情况下声明字符串文字,尽管在 C
中不是这样。但是,使用 const
声明字符串文字可为您带来优势,即编译器通常会在您尝试在第二种情况下修改字符串文字时向您发出警告。
下面一行
char *s = "string";
不会在 gcc
上抛出任何 warning/error 即使 -Wall
。
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 不包括它。
理想情况下,任何修改字符串文字内容的尝试都是未定义行为。因此,始终鼓励在声明字符串文字时使用 const
。
const char *s = "string";
而不是,
char *s = "string";
事实上,在 C++
中不推荐在没有 const
的情况下声明字符串文字,尽管在 C
中不是这样。但是,使用 const
声明字符串文字可为您带来优势,即编译器通常会在您尝试在第二种情况下修改字符串文字时向您发出警告。