Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does it mean to compare pointers using relational operators?

If I have two pointer variables, a and b, what does it mean to to use the statement "a < b"? Is doing so supposed to compare the values of their memory addresses? If so, what would be the order of memory addresses in the computer?

like image 680
Frank Liu Avatar asked Nov 10 '17 18:11

Frank Liu


1 Answers

In C and C++, comparing pointers using relational operators is allowed in the case where you have two pointers into the same array and want to see their relative ordering (there's an exception to this rule that I'll mention in a little bit). For example, imagine that p and q each point somewhere into the middle of array arr, as shown here:

            int arr[9];
            int* p = &arr[1];
            int* q = &arr[4];

    +-----+-----+-----+-----+-----+-----+-----+-----+-----+
arr |     |     |     |     |     |     |     |     |     |
    +-----+-----+-----+-----+-----+-----+-----+-----+-----+
             ^                 ^
             |                 |
             p                 q

In this case, the expression p < q asks "is the index in the array that p points at lower than the index in the array that q points at?" In the above context, the answer is "yes." If p and q were reversed, or if they pointed at the exact same element, the answer would be "no."

The language standards in C and C++ both say that the result of comparing pointers that don't point into the same array is unspecified, which intuitively makes sense because unrelated objects might be scattered around pretty much randomly in memory, or be related in a way that's implementation-dependent (does your stack grow up or down?)

The one exception to this is that you're allowed to compare a pointer one object past the end of an array to a pointer in the array. For example, take a look at this setup:

            int arr[9];
            int* p = &arr[1];
            int* q = &arr[9];

    +-----+-----+-----+-----+-----+-----+-----+-----+-----+
arr |     |     |     |     |     |     |     |     |     |
    +-----+-----+-----+-----+-----+-----+-----+-----+-----+
             ^                                              ^
             |                                              |
             p                                              q

Here, q doesn't point into the array arr. However, the language spec allows you to safely compare p and q. This is why, for example, you can safely use this iterator-style loop in C++:

for (int* itr = arr; itr != arr + /* arr's size */; itr++) {
    ...
}
like image 146
templatetypedef Avatar answered Oct 10 '22 00:10

templatetypedef