Sandeep
Sandeep

Reputation: 1401

Comparing pointers that are not necessarily associated with the same array

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

Answers (1)

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

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.

  • Originally, segmented memory; pointers could ignore the segment and compare faster.
  • Now, it permits certain optimizations. Like assuming compared pointers where derived in certain ways. And if the assumption is violated, the compiler can return anything.
  • Blocks this comparison in constant evaluated code.

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

Related Questions