Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!csd4.milw.wisc.edu!uxc!tank!mimsy!chris From: chris@mimsy.UUCP (Chris Torek) Newsgroups: comp.lang.c Subject: Re: Adding two pointers Message-ID: <17357@mimsy.UUCP> Date: 7 May 89 07:55:01 GMT References: <2765@buengc.BU.EDU> <563@lzaz.ATT.COM> <4093@ficc.uu.net> <17340@mimsy.UUCP> Organization: U of Maryland, Dept. of Computer Science, Coll. Pk., MD 20742 Lines: 28 In article <17340@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@mimsy.umd.edu Path: uunet!mimsy!chris