When is a cast not a cast?

Chris Torek chris at mimsy.UUCP
Thu May 18 03:46:39 AEST 1989


In article <2890 at buengc.BU.EDU> bph at buengc.BU.EDU (Blair P. Houghton) writes:
[char *t, *p, *q; t = p + q;]

>[t] has the property that you can now subtract
>
>    char *pnew, *r;
>    pnew = t - r
>
>and expect pnew to point to the location referred to p that is
>the same offset as q is referred to r.
>
>It's one heck of an optimization if, for some reason, the subtraction
>appears in a loop, and the addition does not.

I cannot think of a realistic example of this.  Anyway, pointer
addition (including the `hidden scaling') is cheap in loops, since
multiplies almost always strength-reduce to adds (and, since the
multiply is by a constant, even if it cannot be reduced to addition, it
*can* be implemented as shift-add-subtract).

Anyway, consider another argument against pointer+pointer addition:

Suppose we have a segmented architecture, in which each object is
always placed in its own segment (which is made just big enough to
address that object and one byte beyond that object).  It would
then be desirable for pointer+integer operations to overflow at
the edge of the segment, so that

	p = &arr[0]; p--;

causes a trap, as does

	p = &arr[sizeof(arr)/sizeof(*arr)]; p++;

But if all pointer arithmetic causes overflow at the end of the
segment, then given pointers (p,q) to the same segment, p+q is likely
to cause an overflow trap.  If the machine is a tagged architecture, it
is possible---even likely---that integer operations will not produce
the proper result, so that p+q (and (p+q)-q) cannot be done as an
unsigned integer add, and might well cost a library call to avoid
overflow traps, sending your hypothetical speed advantage right down
the sewer.
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris at mimsy.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.lang.c mailing list