[cfe-dev] Relational operators on pointers

David Chisnall theraven at sucs.org
Wed Oct 12 14:54:58 PDT 2011


On 12 Oct 2011, at 09:29, Stefan Marr wrote:

> As far as I understand from the standard (Sec. 5.9) and various discussions on comp.std.c++ the use of >=, < etc. is not generally defined for pointers.
> 
> However, it says, it should be defined for pointers on the same array.
> 
> So, what I would expect to work is a comparison of char* >= char* in any circumstances.
> No matter from where I obtain those pointers.

Assuming that the C++ specification says the same thing as the C specification, comparisons between pointers in different object (allocations) is undefined.  This is independent of what you cast the pointers to.  I believe this part of the specification was intended to allow for segmented memory architectures, where pointers do not necessarily have a meaningful ordering outside of an allocation and can be moved around (e.g. Burroughs Large Systems architecture).

If you want to compare two unrelated pointer types, then you should first cast them to an integer type.  Pointer to integer casts (that do not involve truncation) are required to give a unique integer representation of the pointer.  So, if you want to do a comparison between two unrelated pointers as unsigned values, the safest thing to do is cast them to uintptr_t and then do the comparison.

David

-- Sent from my STANTEC-ZEBRA



More information about the cfe-dev mailing list