Reputation: 1401
The C Programming Language
book by Brian W Kernighan & Dennis M. Ritchie
, 2e, states the following on Pages 102-103:
… pointers may be compared under certain circumstances. If p and q point to members of the same array, then relations like ==, !=, <, >=, etc., work properly. But the behavior is undefined for arithmetic or comparisons with pointers that do not point to members of the same array. (There is one exception: the address of the first element past the end of an array can be used in pointer arithmetic).
Does this restriction apply to C++ as well? We have some legacy code that compares pointers (especially void*
) based on their absolute address values, without considering whether or not they belong to the same array, and I am worried whether we need to revisit that code.
Upvotes: 4
Views: 114
Reputation: 275310
Yes. Well, unspecified not undefined, which is much safer.
Converting to int_ptr
is a guaranteed round trip however. Also std::less<>{}( a, b )
is guaranteed to be well behaved and consistent with <
when <
is specified.
This unspecified behaviour permits three things.
However, most compilers do not aggressively blow up when you violate that rule. So it isn't a super high priority fix. At least one compiler actually implements less as a raw <
.
Upvotes: 4