Just for fun, I had a std::list
of const char*
, each element pointing to a null-terminated text string, and ran a std::list::sort()
on it. As it happens, it sort of (no pun intended) did not sort the strings. Considering that it was working on pointers, that makes sense.
According to the documentation of std::list::sort()
, it (by default) uses the operator <
between the elements to compare.
Forgetting about the list for a moment, my actual question is: How do these (>, <, >=, <=) operators work on pointers in C++ and C? Do they simply compare the actual memory addresses?
char* p1 = (char*) 0xDAB0BC47;
char* p2 = (char*) 0xBABEC475;
e.g. on a 32-bit, little-endian system, p1
> p2
because 0xDAB0BC47
> 0xBABEC475
?
Testing seems to confirm this, but I thought it'd be good to put it on StackOverflow for future reference. C and C++ both do some weird things to pointers, so you never really know...
This is just a supplementation.
In C++ 20.3.3/8:
In C 6.5.8/5:
So, I think comparing
char const*
which belong to two different '\0'-terminated-string as in the question is an undefined behavior (in C).In C++, you can't compare just any pointers using the relational operators. You can only compare two pointers that point to elements in the same array or two pointers that point to members of the same object. (You can also compare a pointer with itself, of course.)
You can, however, use
std::less
and the other relational comparison function objects to compare any two pointers. The results are implementation-defined, but it is guaranteed that there is a total ordering.If you have a flat address space, it's likely that pointer comparisons just compare addresses as if they are integers.
(I believe the rules are the same in C, without the comparison function objects, but someone will have to confirm that; I'm not nearly as familiar with C as I am with C++.)
Yes, they just compare memory address.