- 论坛徽章:
- 0
|
有一种说法称一元“&”运算是求地址运算,这种说法既是片面的,也是不严格的,同时对于学习指针有很大的负面作用。理由如下。
在C语言中根本没有“地址”这种数据类型,只有“指针”数据类型,而指针的值才是一个地址。用地址即指针的值的概念偷换指针的概念,显然是以偏概全。更为严重的是,这种说法使得许多人根本就不知道“&d” 是个指针,也掩盖了“&d”指向一块内存的事实,因为“&d”的值仅仅是“d” 所占据的那块内存单元中第一个byte的编号。
====
首先,LZ没错,不过看起来有些想当然了——
ISO/IEC 9899:1999
6.5.3.2 Address and indirection operators
Semantics
3 The unary & operator returns the address of its operand.
按这里的标题,&是address operator(但这个说法用得不普遍,一般直接说unary & operator),可意译为“寻址操作符”,白话一点的形式“求地址运算符”显然也不能算错,至于是否不严格,还要看“地址”的概念是什么。
PS.
P73
79) If &E is a valid pointer expression (where & is the ‘‘address-of ’’ operator, which generates a pointer to
its operand), the expression (&E)->MOS is the same as E.MOS.
这里又成了the ‘‘address-of ’’ operator(这个术语出现的位置都在脚注)。。。
3 The unary & operator returns the address of its operand.——另一个措辞上有问题的地方,到了TC3修订版,改成了
3 The unary & operator yields the address of its operand.
至于地址和指针的说法,因为没找到关于address这个概念的定义,摘录下面关于address constant一段,多少也能看出点问题:
9 An address constant is a null pointer, a pointer to an lvalue designating an object of static
storage duration, or a pointer to a function designator; it shall be created explicitly using
the unary & operator or an integer constant cast to pointer type, or implicitly by the use of
an expression of array or function type. The array-subscript [] and member-access .
and -> operators, the address & and indirection * unary operators, and pointer casts may
be used in the creation of an address constant, but the value of an object shall not be
accessed by use of these operators.
也就是说按C标准的观点,地址(常量)是指针(而不是指地址空间中的整数)——因此也不是“指针的值才是一个地址”(这两个地址是两码事)。既然是指针,那么自然是有类型的,余下的也解释得通了,至少“不严格”不体现在这里。
似乎这里的“地址”概念已经是约定俗成的(就像character constant为什么不叫character literal一样)了,因此说“没有‘地址’这种数据类型”来解释这个问题,有待推敲。
====
越来越觉得ISO C是一桶浆糊……作为对比,ISO C++在讨论unary expression时直接回避了unary operator &的名称问题,语义上明确了“The result of the unary & operator is a pointer to its operand.”(这里倒真不能直接说address,因为有可能指pointer to member),此外直接规定“In particular,
the address of an object of type “cv T” is “pointer to cv T,” with the same cv-qualifiers.”,也就是省了address constant这一容易理解得稀里糊涂的概念(另外还是有address constant expression,不过意义已经有相当的不同了)。此外,the ‘‘address-of ’’ operator在正文(讲bit-field的一段)和索引的位置上也有出现(尽管没有出现在最需要明确的unary expressions一节,但起码可以通过索引而不是脚注找到)——虽然某种意义上也是半斤八两。 |
|