c++ - Is it safe to compare pointers of same type? -
char** buffer{ /* buffer */ }; char* ptr1{buffer[0]}; char* ptr2{buffer[10]}; assert(ptr1 < ptr2);
if 2 pointers point different locations in same buffer, safe compare them?
i want know if range of pointers valid comparing: assert(rangebeginptr < rangeendptr)
.
you can compare pointers relational operators (<
, >
, <=
, >=
) provided both point element of same array, or 1 past array. else unspecified behaviour per c++11 5.9 relational operators
. so, given:
char xyzzy[10]; char plugh[10];
all these specified function correctly:
assert(&(xyzzy[1]) < &(xyzzy[4])); assert(&(xyzzy[9]) < &(xyzzy[10])); // though [10] isn't there.
but these not:
assert(&(xyzzy[1]) < &(xyzzy[15])); assert(&(xyzzy[9]) < &(plugh[3]));
the type doesn't come except has same type if you're comparing 2 elements in same array. if have 2 char *
variables, that's unspecified if point different arrays though have same type.
Comments
Post a Comment