免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
楼主: delimy
打印 上一主题 下一主题

字符串字面值的问题 [复制链接]

论坛徽章:
0
11 [报告]
发表于 2007-05-13 13:20 |只看该作者
原帖由 delimy 于 2007-5-13 12:59 发表

比较想知道这个兼容在C++标准哪一节规定的

在the c++上有说,大概是讲数据类型的那个地方

论坛徽章:
0
12 [报告]
发表于 2007-05-13 13:20 |只看该作者
另外,如果这样:
{char p[] = {'a', 'b', 0};}
同样是栈上的数组,通过hard code的方式初始化,

{char p[] = "ab";}
相比,真的没有哪怕任何一点优势?

论坛徽章:
0
13 [报告]
发表于 2007-05-13 13:24 |只看该作者
原帖由 antigloss 于 2007-5-13 09:28 发表

那编译器可能将指针 p 和 p1 放到寄存器上,但 "abcd" 不会在寄存器上


标准没有规定,就有可能像版主说的那样

论坛徽章:
0
14 [报告]
发表于 2007-05-13 13:30 |只看该作者
所以她们就不是字符串常量了。

论坛徽章:
0
15 [报告]
发表于 2007-05-13 13:32 |只看该作者
原帖由 langue 于 2007-5-13 08:52 发表


如果我指定 register 存储类呢?

.

6.3.2.1 clause 3:
If the array object has register storage class, the behavior is undefined.

评分

参与人数 1可用积分 +2 收起 理由
langue + 2

查看全部评分

论坛徽章:
0
16 [报告]
发表于 2007-05-13 13:33 |只看该作者
忘了一句话
register char a[4] = {0, 1, 2, 3};

这个a只能索引a[i],不能做别的字符串指针操作,比如strlen显然不可用。

论坛徽章:
0
17 [报告]
发表于 2007-05-13 13:43 |只看该作者
注意,是undefined,不是Implementation defined.
undefined behavior
behavior, upon use of a nonportable or erroneous program construct or of erroneous data,
for which this International Standard imposes no requirements

写 register char a[4] 不仅仅是nonportable,在逻辑上就有问题。
这是因为register的变量是不能&的,因为没有地址可言。
可是a在大多数表达式上下文中定义为&a[0]。
所以,不应当使用register char a[4]。

论坛徽章:
0
18 [报告]
发表于 2007-05-13 14:12 |只看该作者
很好,大家在讨论的时候已经注意到对现象追根溯源了。

论坛徽章:
0
19 [报告]
发表于 2007-05-13 21:07 |只看该作者
原帖由 delimy 于 2007-5-13 12:59 发表

比较想知道这个兼容在C++标准哪一节规定的

摘自The C++ Programming Language Special edition,5.2.2 String Literals):

    The type of a string literal is "array of the appropriate number of const characters", so " Bohr" is of type const char[5].

    ...

    A string literal can be assigned to a char*. This is allowed because in previous definitions of C and C++ , the type of a string literal was char*. Allowing the assignment of a string literal to a char* ensures that millions of lines of C and C++ remain valid. It is, however, an error to try to modify a string literal through such a pointer;

论坛徽章:
0
20 [报告]
发表于 2007-05-14 10:29 |只看该作者
原帖由 lgfang 于 2007-5-13 21:07 发表

摘自The C++ Programming Language Special edition,5.2.2 String Literals):

    The type of a string literal is "array of the appropriate number of const characters", so " Bohr& ...

这个我当然知道。我是说C++标准ISO/IEC 14882里的出处。我要的是编译器对此问题的看法。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP