tags:

views:

527

answers:

2
+1  Q: 

Pointer comparison

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
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
+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
thanks for your answer.
fsdemir
Note that the behavior of comparing pointers that don't point to the same array is undefined.
avakar
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
@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
Charles, I checked and I stand corrected (it's section 5.9 in the standard). Thank you.
avakar