4

Do pointers in C and C++ support comparison operators (>, <, etc.) in standard?

I want to compare array positions to be precise.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
fsdemir
  • 93
  • 2
  • 7
  • Dupe of http://stackoverflow.com/questions/1098966/universal-less-for-pointers-in-c-standard among others –  Aug 29 '09 at 08:38

2 Answers2

12

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
  • 35,429
  • 19
  • 126
  • 178
  • 7
    Note that the behavior of comparing pointers that don't point to the same array is undefined. – avakar Aug 29 '09 at 05:47
  • 3
    Note that in C++ the operator() of std::less, std::less_equal, std::greater and std::greater_equal are able to compare pointers to different object meaningfully. – AProgrammer Aug 29 '09 at 06:46
  • 8
    @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. – CB Bailey Aug 29 '09 at 07:25
  • 1
    Charles, I checked and I stand corrected (it's section 5.9 in the standard). Thank you. – avakar Aug 29 '09 at 08:43
  • @CharlesBailey C99 6.5.9.5 (last sentence) "In all other cases, the behavior is undefined." – martinkunev Jul 01 '15 at 10:20
1

Yes, they can be compared.

For example, see "Relational Operators" in standards for further information, 6.5.8 in C99, and 5.9 in old draft of C++ (2006-11).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
maykeye
  • 1,286
  • 1
  • 12
  • 16
  • 2
    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 Aug 29 '09 at 07:28