Is the <(less) operator matched by pointers?

Note. This question is not of a general nature. Full ordering on pointers of the same type can be obtained using std::less .

Accordingly, comparing two pointers with operator< not allowed if they point, for example, to different distributions.

In what sense is it prohibited? Is the implementation defined, undefined, or undefined behavior?

I think I read somewhere that it is not listed. Implementation is not required to document behavior, but there must be some kind of behavior. Thus, this means that comparing any two pointers is still legal, but does not necessarily give a general order. Does this mean that we should still get a consistent result when comparing two of the same two pointers twice? . In the general case: does the same unspecified behavior cause twice in the application, always gives 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? 
+5
source share
2 answers

Comparison of two unrelated pointers (that is, pointers that do not point to the same memory or do not point to different parts of the same "array") can only be done using equality == and inequality != . All other comparisons are unspecified.

If you have two pointers pointing to the same place or inside the same array, you can compare them using relative operators.

So, if you have, for example,

 int* p1 = new int[10]; int* p2 = new int[5]; 

you can use == and != to compare pointers p1 and p2 .

But if you have

 int a = new int[10]; int* p1 = &a[0]; int* p2 = &a[3]; 

then you can also use < and > (and of course, <= and >= ) to compare p1 and p2

+4
source

Comparing pointers, as shown in your example, makes little sense, because the values ​​of "a" and "b" depend on how the data is stored in memory, and not on the content stored in this place.

Pointers are addresses in memory (usually stored as a 32-bit integer). If you do not change any of them, comparing them will return the same result. You may not know what the result is, but you will know that everything will be the same every time.

Therefore, in your case, you will get the same result for both b1 and b2, so the statement will pass.

Here is an example where comparing pointers makes sense:

 int data[1000]; int *end = data + 50; for (int *c = data; c < end; c++) ... use *c 
-1
source

Source: https://habr.com/ru/post/1268602/


All Articles