Pointer Comparison and Portability

nw at vaxine.UUCP nw at vaxine.UUCP
Thu Feb 12 04:15:14 AEST 1987


Consider the following C function:

        same_char (p, q)
        char *p;
        char *q;
        {
                return (p == q);
        }

Does this function only return a non-zero value when p and q point
to the same physical character?  This may seem like a silly question,
but I haven't found an iron-clad answer in K & R yet.   I quote:

K & R page 98 (emphasis mine):

        If p and q point to members of the SAME ARRAY, then relations
        like <, >=, etc., work properly.

                p < q

        is true, for example, if p points to an earlier member of the array
        than does q.  The relations == and != also work.

It goes on to say that all bets are off for comparisons of pointers between
different arrays.  Thus, if p and q pointed inside different character arrays,
it would appear that comparison between those pointers, even for equality,
is undefined.

Obviously (?) the intent of the warning was that one should not assume
anything about the ordering of distinct objects in memory.  Unfortunately,
I don't see any guarantee that every object has a unique address as
defined by the pointer comparison operation.

Imagine a hypothetical segmented machine where every C object were
allocated in its own separate segment.  Essentially, my question
boils down to this:  On such a machine, must pointer comparison
be implemented by comparing both segment base and offset within
segment, or is it allowable to simply compare offset within segment?

I certainly wouldn't advocate such an implementation, but I'm disturbed that
I can't seem to rule it out.

Neil Webber     Automatix Inc (or current resident)     Billerica MA
                        {decvax,allegra}!encore!vaxine!nw



More information about the Comp.lang.c mailing list