为什么当你用字符串初始化一个没有 const 的数组时 gcc 不给出警告?
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;
}
我期待在 char *array[] = {"Hello", "World", NULL};
中收到警告,因为这些字符串的字符是只读的,但编译器没有给我警告。所以基本上编译器让我 "cast" a const char
到 char
a 没有警告。
当将 const char
传递给在 print(constArray);
中接收 char
的函数时,换句话说,"casting" a const char
,到 char
编译器确实给了我一个警告。我希望编译器在两种情况下都给我一个警告,或者在两种情况下都不会给我警告,但在一种情况下不会,在另一种情况下不会。
我认为这个警告很重要,有助于防止 array[0][0] = '!';
中的错误。那么为什么我在第一次初始化时没有收到警告?
So why I don't get a warning in the first initialization?
因为字符串文字的类型是 char
的数组,而不是 const char
的数组,尽管修改此类数组的元素会产生未定义的行为。这是从 C 的最初几天开始的,当时还没有 const
。我确信它在现代 C 中的持久性是围绕着如果类型被更改会出现的不兼容的程度和范围。
然而,对于个别程序,GCC 可以帮助您。如果你打开它的 -Wwrite-strings
选项,那么它确实会给出字符串文字类型 const char [
length
]
,结果是您提出的构造将引发警告。
编译器不会警告您,因为 C 标准不要求字符串文字是 const。
Why doesn't the compiler detect and produce errors when attempting to modify char * string literals?
Why do compilers allow string literals not to be const?
#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;
}
我期待在 char *array[] = {"Hello", "World", NULL};
中收到警告,因为这些字符串的字符是只读的,但编译器没有给我警告。所以基本上编译器让我 "cast" a const char
到 char
a 没有警告。
当将 const char
传递给在 print(constArray);
中接收 char
的函数时,换句话说,"casting" a const char
,到 char
编译器确实给了我一个警告。我希望编译器在两种情况下都给我一个警告,或者在两种情况下都不会给我警告,但在一种情况下不会,在另一种情况下不会。
我认为这个警告很重要,有助于防止 array[0][0] = '!';
中的错误。那么为什么我在第一次初始化时没有收到警告?
So why I don't get a warning in the first initialization?
因为字符串文字的类型是 char
的数组,而不是 const char
的数组,尽管修改此类数组的元素会产生未定义的行为。这是从 C 的最初几天开始的,当时还没有 const
。我确信它在现代 C 中的持久性是围绕着如果类型被更改会出现的不兼容的程度和范围。
然而,对于个别程序,GCC 可以帮助您。如果你打开它的 -Wwrite-strings
选项,那么它确实会给出字符串文字类型 const char [
length
]
,结果是您提出的构造将引发警告。
编译器不会警告您,因为 C 标准不要求字符串文字是 const。
Why doesn't the compiler detect and produce errors when attempting to modify char * string literals?
Why do compilers allow string literals not to be const?