On Tue, Sep 13, 2005 at 11:22:18AM +0100, chris jefferson wrote:
> I realise that according to the C++ standard it isn't legal to compare
> two pointers which are not from the same array. Is anyone aware of
> anything in g++ which would actually forbid this, and if there is any
> way of checking if will be valid?
> 
> I want to be able to perform two main operations. Firstly to compare any
> pair of pointers with ==, and also to write code like:
> 
> template<typename T>
>   bool
>   in_range(T* begin, T* end, T* value)
>   { return (begin <= value) != (end <= value); }
> 
> Where value may be a pointer not from the same array as begin and end.
> 
> Apologises for sending this question to the main gcc list, but I want to
> submit such code to the debugging part of libstdc++-v3, and wanted to
> check if any optimisations may make use the fact comparing pointers from
> different arrays is undefined.

If two pointers to a T* are in the same array, their difference [in
bytes] must be 0 modulo sizeof(T).  If they aren't, and sizeof(T) >
alignof(T), then it doesn't have to be.  I'm pretty sure GCC can
optimize based on this information.

This bit binutils, in the form of a crash in a hash function on
Solaris.  I think that was pointer subtraction, rather than comparison,
however.

Perhaps someone who remembers this problem more clearly than
I do can chip in if I've gotten it totally wrong.

-- 
Daniel Jacobowitz
CodeSourcery, LLC

Reply via email to