C++ Result of some pointer comparisons


Example

If two pointers are compared using <, >, <=, or >=, the result is unspecified in the following cases:

  • The pointers point into different arrays. (A non-array object is considered an array of size 1.)

    int x;
    int y;
    const bool b1 = &x < &y;            // unspecified
    int a[10];
    const bool b2 = &a[0] < &a[1];      // true
    const bool b3 = &a[0] < &x;         // unspecified
    const bool b4 = (a + 9) < (a + 10); // true
                                        // note: a+10 points past the end of the array
    
  • The pointers point into the same object, but to members with different access control.

    class A {
      public:
        int x;
        int y;
        bool f1() { return &x < &y; } // true; x comes before y
        bool f2() { return &x < &z; } // unspecified
      private:
        int z;
    };