Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any case when "ptr1 - ptr2 > 0" would differ from "ptr1 > ptr2"?

Tags:

Assuming the two pointers of the same type point within the same array (or the same object) so that both subtraction of two pointers and comparison are valid... is there any case where

if(ptr1 - ptr2 > 0) 

would behave differently from

if(ptr1 > ptr2) 

or are they at all times equivalent?

like image 345
sharptooth Avatar asked Apr 20 '15 11:04

sharptooth


1 Answers

Yes, there is such a case where the two will not behave the same.

Pointer difference is signed [expr.add]:

When two pointers to elements of the same array object are subtracted, the result is the difference of the subscripts of the two array elements. The type of the result is an implementation-defined signed integral type; this type shall be the same type that is defined as std::ptrdiff_t in the <cstddef> header

but with two caveats:

As with any other arithmetic overflow, if the result does not fit in the space provided, the behavior is undefined.

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.

On the comparison side, we have [expr.rel]:

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

The last bullet point there gives us a difference. Consider:

struct A {     int x, y; }  A a; int *px = &a.x, *py = &a.y 

px > py is defined but px - py > 0 is undefined.

There is also of course the integer overflow case, if you have an enormous array:

array[0] > array[PTRDIFF_MAX + 10]         // defined array[0] - array[PTRDIFF_MAX + 10] > 0     // undefined 

Outside of those two cases, if the two pointers point to the same array (or one-past-the-end), the two expressions are equivalent. If the two pointers point to different arrays, then both are undefined.

like image 97
Barry Avatar answered Oct 31 '22 13:10

Barry