字面量到底在哪里? (请参见下面的示例)
我无法修改文字,因此它应该是const char *,尽管编译器允许我使用char *,但即使有大多数编译器标志,我也没有警告。
从const char *类型隐式转换为char *类型会给我一个警告,请参阅下文(在GCC上进行了测试,但在VC ++ 2010上的行为类似)。
另外,如果我修改const char的值(以下技巧可以使GCC更好地警告我),它不会出错,甚至可以在GCC上进行修改和显示(即使我认为它仍然是未定义的行为,我想知道为什么它对文字没有做同样的事情)。这就是为什么我要问这些文字存储在哪里,以及更常见的const应该存储在哪里?
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的基本原理,委员会中有些人希望字符串文字可以修改,因此该标准并未明确禁止这样做。
请注意,C ++中的情况有所不同。在C ++中,字符串文字是const char数组。但是,C ++允许从const char *转换为char *。不过,该功能已被弃用。
关于c++ - 为什么编译器不允许字符串文字为const?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32807364/