[英]Why gcc does not give a warning when you initialize an array without const with strings?
#include <stdio.h>
void print(char *strings[]) {
while (*strings) printf("%s\n", *strings++);
}
int main(int argc, char *argv[]) {
char *array[] = {"Hello", "World", NULL}; // No warning?
const char *constArray[] = {"Hello", "World", NULL};
print(constArray); // Warning!
//constArray[0][0] = '!'; Compile time error
array[0][0] = '!'; // Run time error
return 0;
}
I was expecting to get a warning in char *array[] = {"Hello", "World", NULL};
我期望在
char *array[] = {"Hello", "World", NULL};
得到警告char *array[] = {"Hello", "World", NULL};
because the characters of those strings are read only, but the compiler does not give me a warning about that. 因为这些字符串的字符是只读的,但是编译器没有为此警告我。 So basically the compiler is letting me "cast" a
const char
to a char
a without warning. 因此,基本上,编译器让我在没有警告的情况下将
const char
转换为char
a。
When passing a const char
to a function that receives a char
in print(constArray);
当通过一个
const char
到其接收的功能char
在print(constArray);
, in other words, "casting" a const char
, to a char
the compiler does give me a warning. ,换句话说,将
const char
“ cast”到char
编译器确实会警告我。 I was expecting the compiler to give me a warning in both cases or in neither, but not in one case and not the other. 我期望编译器在两种情况下都不会给我警告,但在任何一种情况下都不会给我警告,而在另一种情况下则不会给我警告。
I think this warning is important to help prevent errors like in array[0][0] = '!';
我认为此警告很重要,有助于防止出现
array[0][0] = '!';
. 。 So why I don't get a warning in the first initialization?
那么,为什么在第一次初始化时没有收到警告?
So why I don't get a warning in the first initialization?
那么,为什么在第一次初始化时没有收到警告?
Because the type of a string literal is array of char
, not array of const char
, notwithstanding the fact that modifying the elements of such an array produces undefined behavior. 由于字符串文字的类型是
char
数组,而不是const char
数组,尽管修改此类数组的元素会产生未定义的行为。 This comes down from the very first days of C, when there was no const
. 这是从C的第一天开始的,当时没有
const
。 I'm sure its persistence into modern C revolves around the magnitude and scope of the incompatibility that would arise if the type were changed. 我确信它对现代C语言的持久性围绕着类型更改会引起的不兼容的程度和范围。
With respect to individual programs, however, GCC can help you out. 但是,对于个别程序,GCC可以为您提供帮助。 If you turn on its
-Wwrite-strings
option then it will indeed give string literals type const char [
length
]
, with the result that a construct such as you presented will elicit a warning. 如果您打开它的
-Wwrite-strings
选项,那么它的确会给出类型为const char [
length
]
字符串文字,其结果是,您所提出的结构将引发警告。
The compiler doesn't warn you because the C standard doesn't require that string literals be const. 编译器不会警告您,因为C标准不需要字符串文字为const。
Why doesn't the compiler detect and produce errors when attempting to modify char * string literals? 尝试修改char *字符串文字时,编译器为什么不检测并产生错误?
Why do compilers allow string literals not to be const? 为什么编译器不允许字符串文字成为const?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.