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 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.
int* p1 = new int[10];
int* p2 = new int[5];
you can only use ==
and !=
to compare the pointers p1
and p2
.
But if you have
int a = new int[10];
int* p1 = &a[0];
int* p2 = &a[3];
then you can use also <
and >
(and of course <=
and >=
) to compare p1
and p2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With