Xref: utzoo comp.sys.ibm.pc:22204 comp.sys.intel:599 Path: utzoo!attcan!uunet!lll-winken!lll-tis!ames!killer!chasm From: chasm@killer.DALLAS.TX.US (Charles Marslett) Newsgroups: comp.sys.ibm.pc,comp.sys.intel Subject: Re: correct code for pointer subtraction Summary: If they did it right the difference would be correct Message-ID: <6420@killer.DALLAS.TX.US> Date: 13 Dec 88 23:58:28 GMT References: <597@mks.UUCP> <3845@pt.cs.cmu.edu> Organization: The Unix(R) Connection, Dallas, Texas Lines: 47 In article <3845@pt.cs.cmu.edu>, ralf@b.gp.cs.cmu.edu (Ralf Brown) writes: => In article <597@mks.UUCP> egisin@mks.UUCP (Eric Gisin) writes: => -How come I can't find a compiler that generates correct => -code for pointer subtraction in C on 8086s? => -Neither Turbo, Microsoft, or Watcom do it right. => -Here's an example: => - => -struct six { => - int i[3]; => -}; => -int diff(struct six far* p, struct six far* q) { => - return p - q; => -} => -main(void) { => - struct six s[1]; => - printf("%d\n", diff(s+10000, s)); /* 10000 */ => - printf("%d\n", diff(s, s+100)); /* -100 */ => -} => - => -All of the compilers I tried computed a 16 bit difference, => -then sign extended it before dividing. => -This does not work if the pointers differ by more than 32K. => => In addition to HUGE model, which someone already pointed out, I would like to => mention that K&R only guarantees valid results for pointer subtractions => between pointers to the SAME array. In non-HUGE models, the largest object => is 64K, so for multi-byte data types, the result is correct (since they can't => differ by more than 32K objects). For char arrays, you would have an => ambiguity as to which pointer points lower in the array. I must disagree, the error occurs if the pointers differ by 32K bytes -- it is independent of the size of an element. The result is that if you use pointer subtraction in you code, you must be K&R *AND* smaller than 32K bytes. I finally wrote an assembly routine that takes two pointers and an element size and returns the difference (as an integer). That was just because the compiler writers were all too lazy to do the code generation correctly! By the way, MSC 5.1 does it wrong in small model too! Charles Marslett chasm@killer.dallas.tx.us => -- => {harvard,uunet,ucbvax}!b.gp.cs.cmu.edu!ralf -=-=- AT&T: (412)268-3053 (school) => ARPA: RALF@B.GP.CS.CMU.EDU |"Tolerance means excusing the mistakes others make. => FIDO: Ralf Brown at 129/31 | Tact means not noticing them." --Arthur Schnitzler => BITnet: RALF%B.GP.CS.CMU.EDU@CMUCCVMA -=-=- DISCLAIMER? I claimed something? => --