为什么编译器允许字符串文字不是常量?
内存中的文字到底在哪里?(见下面的例子)
And where are literals in memory exactly? (see examples below)
我无法修改文字,因此它应该是 const char*,尽管编译器允许我使用 char*,但即使使用大多数编译器标志,我也没有警告.
I cannot modify a literal, so it would supposedly be a const char*, although the compiler let me use a char* for it, I have no warnings even with most of the compiler flags.
而将 const char* 类型隐式转换为 char* 类型会给我一个警告,请参见下文(在 GCC 上测试,但在 VC++2010 上的行为类似).
Whereas an implicit cast of a const char* type to a char* type gives me a warning, see below (tested on GCC, but it behaves similarly on VC++2010).
此外,如果我修改 const char 的值(使用下面的技巧,GCC 最好给我一个警告),它不会出错,我什至可以在 GCC 上修改和显示它(即使我猜它仍然是一个未定义的行为,我想知道为什么它没有对文字做同样的事情).这就是为什么我要问这些文字存储在哪里,以及更常见的 const 存储在哪里?
Also, if I modify the value of a const char (with a trick below where GCC would better give me a warning for), it gives no error and I can even modify and display it on GCC (even though I guess it is still an undefined behavior, I wonder why it did not do the same with the literal). That is why I am asking where those literal are stored, and where are more common const supposedly stored?
const char* a = "test";
char* b = a; /* warning: initialization discards qualifiers
from pointer target type (on gcc), error on VC++2k10 */
char *c = "test"; // no compile errors
c[0] = 'p'; /* bus error when execution (we are not supposed to
modify const anyway, so why can I and with no errors? And where is the
literal stored for I have a "bus error"?
I have 'access violation writing' on VC++2010 */
const char d = 'a';
*(char*)&d = 'b'; // no warnings (why not?)
printf("%c", d); /* displays 'b' (why doesn't it do the same
behavior as modifying a literal? It displays 'a' on VC++2010 */
推荐答案
C 标准不禁止修改字符串文字.它只是说如果进行了尝试,行为是未定义的.根据 C99 的基本原理,委员会中有人希望字符串文字是可修改的,因此标准并未明确禁止.
The C standard does not forbid the modification of string literals. It just says that the behaviour is undefined if the attempt is made. According to the C99 rationale, there were people in the committee who wanted string literals to be modifiable, so the standard does not explicitly forbid it.
请注意,在 C++ 中情况有所不同.在 C++ 中,字符串文字是 const char 的数组.但是,C++ 允许从 const char * 转换为 char *.不过,该功能已被弃用.
Note that the situation is different in C++. In C++, string literals are arrays of const char. However, C++ allows conversions from const char * to char *. That feature has been deprecated, though.
相关文章