Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Similarly, comparing pointers using the relational operators <<=>=, and > gives the positions of the pointers relative to each other. Subtracting or comparing pointers that do not refer to the same array results in undefined behavior.

Page properties
hiddentrue

This may be true for C, but is not true for C++ as best I can tell. [expr.rel]p3 says:

Comparing pointers to objects is defined as follows:
— If two pointers point to different elements of the same array, or to subobjects thereof, the pointer to the element with the higher subscript compares greater.
— 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 (Clause 11) and provided their class is not a union.

[expr.rel]p4 says:

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. 

The way I read this is that if two pointers do not fall into one of the three categories from p3, then we fall into the "Otherwise" clause of p4, and so the result is unspecified (not undefined). Another interesting (pedantic) reading is that two pointers that point to one past the last element of the same array cannot be compared with the relational operator without exhibiting unspecified behavior. Eg)

Code Block
unsigned char buf[3];
unsigned char *buf_end = &buf[3]; // One past end
if (buf_end <= buf_end) { // Unspecified result, but could reasonably expect true
}

This might be something to bring up in CWG.

Comparing pointers using the equality operators == and != has well-defined semantics regardless of whether or not either of the pointers is null, points into the same object, or points one past the last element of an array object or function.

...

[Banahan 03] Section 5.3, "Pointers," and Section 5.7, "Expressions involving pointers"
[ISO/IEC 14882-2003] Section 5.7 "Additive operators"
[MITRE 07] CWE ID 469, "Use of Pointer Subtraction to Determine Size"

...

      06006. Containers (CTR)