Adding two pointers

Chris Torek chris at mimsy.UUCP
Sun May 7 17:55:01 AEST 1989


In article <17340 at mimsy.UUCP>, regarding finding the midpoint of two
pointers, I wrote:
>So the compiler should reduce this to
>
>	sub	base,low,r0
>	sub	base,high,r1
>	add	r0,r1,r0
>	div	r0,$2,r0
>	add	r0,base,mid
>
>which is what we need anyway (to avoid overflow).

RMS listened, and pointed out that this is wrong.  The result of
the divide can be halfway between two valid pointer offsets.  (E.g.,
if size is 4 and low-base=4 and high=base-8---i.e., low is &arr[1]
and high is &arr[2]---then (4+8)/12 is 6, rather than the 4 that we
should get.) This can be fixed by rounding down to the nearest multiple
of `size' (here,

	and	r0,$~3,r0

between the final `div' and `add'); in the worst case this requires
a divide and a multiply anyway.  This particular sequence is probably
not common enough to bother with, although the fact that pointer
subtraction implies remainderless division does seem worth noting.
-- 
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