Does pointers in C and C++ support comparison operators (>, <, etc.) in standard? I want to compare array positions to be precise.
+2
A:
Yes, they can be compared.
ADDED: For example, see "Relational Operators" in standards for further info. 6.5.8 in C99, 5.9 in old draft of c++ (november, 2006)
maykeye
2009-08-29 04:44:31
With the caviat that the pointers must point to the same contiguous chunk of memory that was allocated in one allocation. Two random pointers can not be compared.
Martin York
2009-08-29 07:28:40
+10
A:
In a contiguous array comparing memory offsets (pointers) is OK. If your array is implemented as a linked list (for example) the nodes could be all over memory so pointer comparison is nonsensical.
fbrereto
2009-08-29 04:44:56
Note that the behavior of comparing pointers that don't point to the same array is undefined.
avakar
2009-08-29 05:47:12
Note that in C++ the operator() of std::less<T*>, std::less_equal<T*>, std::greater<T*> and std::greater_equal<T*> are able to compare pointers to different object meaningfully.
AProgrammer
2009-08-29 06:46:03
@avakar: Technically, the behaviour is not _undefined_ (the result must of the comparison must be a bool, the implementation shouldn't randomly crash or anything); the result of the comparison is _unspecified_ - i.e. it could be true or false and the implementation doesn't have to document what the result is.
Charles Bailey
2009-08-29 07:25:25
Charles, I checked and I stand corrected (it's section 5.9 in the standard). Thank you.
avakar
2009-08-29 08:43:36