Pointers in comparison expressions

Michael Meissner gcc-mail@the-meissners.org
Tue Jul 12 23:27:00 GMT 2005


On Wed, Jul 13, 2005 at 12:38:11AM +0200, Falk Hueffner wrote:
> Erik Trulsson <ertr1013@student.uu.se> writes:
> 
> > On Tue, Jul 12, 2005 at 03:08:54PM -0700, Joe Buck wrote:
> >> On Tue, Jul 12, 2005 at 11:42:23PM +0200, Erik Trulsson wrote:
> >> > Pointer subtraction is only well defined if both pointers point to elements
> >> > in the same array (or one past the end of the array).  Otherwise the
> >> > behaviour is undefined.
> >> 
> >> While this is correct, there are certain cases that the standard leaves
> >> undefined but that nevertheless can be useful; for example, pointer
> >> subtraction can be used to estimate the amount of stack in use (of
> >> course, it is necessary to know if the stack grows upward or downward).
> >> 
> >> Similarly, in an OS kernel, comparing pointers may make sense.
> >
> > Yes, there are some situations where it can be useful to compare pointers
> > to different objects, but then you need to make sure that the compiler you
> > use actually supports that.
> >
> > I believe most C compilers support it in practice, but few, if any, have
> > actually documented it as a supported extension to C.
> 
> I don't think we should, either. People who want to do this can just
> cast both pointers to size_t.

Note, it is not guaranteed that size_t is big enough to hold a pointer.  In
particular, cast your minds back to when we had 16 and 32-bit x86 code, and
some compilers had different memory models like near/far (which was the case
when the C90 standard was defined).  Size_t could be 16-bits, since the
compiler would not allow any item bigger than 32K to be created, but pointers
could have the segment pointer as well as the bottom 16-bits.  If a compiler
knew size_t was restricted to 16 bits, it could eliminate code to normalize the
pointer before doing the comparison, and just do a simple subtraction.

-- 
Michael Meissner
email: gnu@the-meissners.org
http://www.the-meissners.org



More information about the Gcc mailing list