Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is operator< (less than) on pointers consistent?

Tags:

c++

pointers

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?
like image 722
haslersn Avatar asked Jun 06 '17 18:06

haslersn


1 Answers

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

like image 55
Some programmer dude Avatar answered Nov 14 '22 22:11

Some programmer dude