8

Stroustrup 的 C++ Programming Language 3rd edition 说,

仅当两个指针都指向同一数组的元素时才定义指针的减法(尽管该语言没有快速的方法来确保这种情况)。当从另一个指针中减去一个指针时,结果是两个指针之间的数组元素数(整数)。可以将整数添加到指针或从指针中减去整数;在这两种情况下,结果都是一个指针值。 如果该值不指向与原始指针相同的数组元素或其他元素,则使用该值的结果是未定义的。

例如:

void f ()
{
    int v1 [10];
    int v2 [10];
    int i1 = &v1[5] - &v1[3];   // i1 = 2
    int i2 = &v1[5] - &v2[3];   // result undefined
}

我正在阅读维基百科上未指明的行为。它说

在 C 和 C++ 中,仅当指针指向同一对象的成员或同一数组的元素时,才严格定义指向对象的指针的比较。

例子:

int main(void)
{
  int a = 0;
  int b = 0;
  return &a < &b; /* unspecified behavior in C++, undefined in C */
}

所以,我很困惑。哪一个是正确的?维基百科或 Stroustrup 的书?C++ 标准对此有何规定?

纠正我如果我误解了什么。

4

1 回答 1

13

请注意,指针减法和指针比较是不同的操作,具有不同的规则。

C++14 5.6/6,关于减指针:

除非两个指针都指向同一个数组对象的元素或指向数组对象最后一个元素的元素,否则行为是未定义的。

C++14 5.9/3-4:

比较指向对象的指针定义如下:

  • 如果两个指针指向同一数组的不同元素或其子对象,则指向具有较高下标的元素的指针比较大。

  • If one pointer points to an element of an array, or to a subobject thereof, and another pointer points one past the last element of the array, the latter pointer compares greater.

  • If two pointers point to different non-static data members of the same object, or to subobjects of such members, recursively, the pointer to the later declared member compares greater provided the two members have the same access control and provided their class is not a union.

If two operands p and q compare equal (5.10), p<=q and p>=q both yield true and p<q and p>q both yield false. Otherwise, if a pointer p compares greater than a pointer q, p>=q, p>q, q<=p, and q<p all yield true, and p<=q, p<q, q>=p, and q>p all yield false. Otherwise, the result of each of the operators is unspecified.

于 2015-08-02T17:50:39.823 回答