Is pointer comparison undefined or unspecified behavior in C++?

后端 未结 1 717
一向
一向 2020-11-30 13:06

The C++ Programming Language 3rd edition by Stroustrup says that,

Subtraction of pointers is defined only when both pointers point to elements of th

相关标签:
1条回答
  • 2020-11-30 13:30

    Note that pointer subtraction and pointer comparison are different operations with different rules.

    C++14 5.6/6, on subtracting pointers:

    Unless both pointers point to elements of the same array object or one past the last element of the array object, the behavior is undefined.

    C++14 5.9/3-4:

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

    0 讨论(0)
提交回复
热议问题