为什么编译器允许字符串不为const? [英] Why do compilers allow string literals not to be const?

查看:154
本文介绍了为什么编译器允许字符串不为const?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在哪里是在完全相同的内存文字? (见下面的例子)

我不能修改文字,所以它会被认为一个const char *,但是编译器让我用它一个char *,我没有警告,甚至与大多数编译器标志。

而一个const char *类型为char *类型的隐式转换给了我一个警告,见下文(GCC上进行测试,但它VC ++ 2010年类似的行为)。

另外,如果我修改一个const char的值(下面,如果GCC会更好地给我一个警告的伎俩),它使没有错误,我甚至可以修改和显示它在海湾合作委员会(即使我想这仍然是一个不确定的行为,我不知道为什么它没有这样做字面相同)。这就是为什么我问的其中的文字存储,哪里是所谓存储更常见常量?

 为const char * A =测试;
字符* B = A; / *警告:初始化丢弃预选赛
  指针目标类型(海合会),在VC ++ 2K10错误* /烧焦* C =测试; //没有编译错误
C [0] ='P';当执行(我们不应该/ *总线错误
  修改常量无论如何,所以为什么我并没有错误?和在哪里
  文字保存我有一个总线错误?
  我对访问冲突写VC ++ 2010 * /为const char D ='A';
*(字符*)和D ='B'; //没有警告(为什么不呢?)
的printf(%C,D); / *显示'B'(为什么没有这样做
  行为改变的文字?它显示A上的VC ++ 2010 * /


解决方案

C标准并不禁止字符串文字的修改。它只是说,如果尝试的行为是不明确的。按照C99理,里面的人谁想要字符串文字可修改委员会,所以标准没有明确禁止它。

请注意,这种情况在C ++不同。在C ++中,字符串文字是常量字符数组。然而,C ++允许从为const char *转换为char *。该功能已经pcated德$ P $,虽然。

And where are literals in memory exactly? (see examples below)

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.

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).

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 */

解决方案

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.

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.

这篇关于为什么编译器允许字符串不为const?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆