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

C ++ programming language 3rd edition of Stroustrup says that

Subtraction of pointers is determined only when both pointers point to elements of the same array (although the language does not have a quick way in this case). When subtracting one pointer from another, the result is the number of elements in the array between the two pointers (integer). You can add an integer to the pointer or subtract the integer from the pointer; in both cases, the result is the value of the pointer. If this value does not point to an element of the same array as the source pointer or one after it, the result of using this value is undefined.

For instance:

void f () { int v1 [10]; int v2 [10]; int i1 = &v1[5] - &v1[3]; // i1 = 2 int i2 = &v1[5] - &v2[3]; // result undefined } 

I read about unspecified behavior on Wikipedia. It says that

In C and C ++, comparing pointers with objects is strictly defined if pointers point to members of the same object or to elements of the same array.

Example:

 int main(void) { int a = 0; int b = 0; return &a < &b; /* unspecified behavior in C++, undefined in C */ } 

So, I'm confused. Which one is correct? Wikipedia or Straustrup book? What does the C ++ standard say about this?

Correct me if I donโ€™t understand something.

+6
source share
1 answer

Note that subtracting a pointer and comparing pointers are different operations with different rules.

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

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

C ++ 14 5.9 / 3-4:

A comparison of pointers with objects is defined as follows:

  • If two pointers point to different elements of the same array or to its subobjects, the pointer to the element with a higher index is compared more.

  • If one pointer points to an element of the array or its subobject, and another pointer points one after the last element of the array, the last pointer compares more.

  • If two pointers point to different non-static data elements of the same object or to subobjects of such members, recursively, a pointer to a later declared element is compared more if two elements have the same access control and if their class is not a union.

If two operands p and q compare the same (5.10), p<=q and p>=q , both give true and p<q and p>q , and both values โ€‹โ€‹give false. Otherwise, if the pointer p compares more than the pointer q , p>=q , p>q , q<=p and q<p , all give true and p<=q , p<q , q>=p , and q>p all give false . Otherwise, the result of each of the operators is not specified.

+10
source

All Articles