In C and C ++, comparing pointers using relational operators is allowed when you have two pointers in the same array and you want to see their relative order (there is an exception to this rule, which I will talk about a bit). For example, imagine that p and q each point is somewhere in the middle of the arr array, as shown below:
int arr[9]; int* p = &arr[1]; int* q = &arr[4]; +-----+-----+-----+-----+-----+-----+-----+-----+-----+ arr | | | | | | | | | | +-----+-----+-----+-----+-----+-----+-----+-----+-----+ ^ ^ | | pq
In this case, the expression p < q asks "is the index in the array that p points to a lower value than the index in the array that q points to?" In the above context, the answer is yes. If p and q were canceled, or if they pointed to the same element, the answer would be no.
The language standards in C and C ++ say that the result of comparing pointers that do not point to the same array is not defined, which intuitively makes sense, since unrelated objects can be scattered largely randomly in memory or be connected depending on implementation (does your stack grow up or down?)
The one exception is that you are allowed to compare the pointer to one object beyond the end of the array with the pointer in the array. For example, look at this setting:
int arr[9]; int* p = &arr[1]; int* q = &arr[9]; +-----+-----+-----+-----+-----+-----+-----+-----+-----+ arr | | | | | | | | | | +-----+-----+-----+-----+-----+-----+-----+-----+-----+ ^ ^ | | pq
Here q does not indicate an arr array. However, the language specification 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 + ; itr++) { ... }
templatetypedef
source share