Note: This question is not about total order. A total order on pointers of the same type can be obtained using std::less
.
According to this, comparing two pointers with operator<
isn't allowed if they point for example into different allocations.
In which sense isn't it allowed? Is it implementation defined, unspecified or undefined behaviour?
I think I read somewhere that it's unspecified. An implementation isn't required to document what the behaviour is, but there must be some behaviour. So that would mean, comparing any two pointers is still legal, but doesn't neccessarily yield a total order. Does that mean, that we still have to get a consistent result, when comparing the same two pointers twice? The general case would be: Does invoking the same unspecified behaviour twice within an application always yield the same result?
int i1, i2;
int* a = &i1;
int* b = &i2;
bool b1 = a < b; // unspecified, right?
bool b2 = a < b;
assert(b1 == b2); // Is this guaranteed to be true?
Comparing pointers as shown in your example makes little sense because "a" and "b" value depends on how is the data stored in memory, not on the content stored in that location.
Pointers are addresses in memory (usually stored as 32 bit integer). Unless you change any of them, their comparison will return the same result. You might not know what that result is, but you'll know that it'll be the same every time.
Therefore, in your case, you will get the same result for both b1 and b2, so the assertion will pass.
Here is an example where comparing pointers does make sense:
Comparing two unrelated pointers (i.e. pointers not pointing to the same memory, or not pointing to different parts of the same "array") can only be done using equality
==
and inequality!=
. All other comparison is unspecified.If you have two pointers pointing to the same place, or inside the same array, then you can compare them using the relative operators.
So if you have e.g.
you can only use
==
and!=
to compare the pointersp1
andp2
.But if you have
then you can use also
<
and>
(and of course<=
and>=
) to comparep1
andp2