Xref: utzoo comp.sys.ibm.pc:22779 comp.sys.intel:641 Path: utzoo!attcan!uunet!lll-winken!lll-lcc!ames!haven!vrdxhq!bms-at!stuart From: stuart@bms-at.UUCP (Stuart Gathman) Newsgroups: comp.sys.ibm.pc,comp.sys.intel Subject: Re: correct code for pointer subtraction Summary: Everybody is wrong - BORLAND: please read this Keywords: C pointer math DAMN WELL IS A BUG!!!! Message-ID: <147@bms-at.UUCP> Date: 5 Jan 89 03:55:21 GMT References: <597@mks.UUCP> <3845@pt.cs.cmu.edu> <18123@santra.UUCP> <51@rpi.edu> Organization: Business Management Systems, Inc., Fairfax, VA Lines: 52 In article <51@rpi.edu>, kyriazis@rpics (George Kyriazis) writes: > division to get the result instead of the unsigned that it should do. Unsigned division will not help one whit. You need 17 bits precision. sizeof (type) == 2^n: mov ax,ptr1 sub ax,ptr2 rcr ax,1 sra ax,1 ;n-1 times, possibly none sizeof (type) == 2*n: mov ax,ptr1 sub ax,ptr2 rcr ax,1 cwd mov bx,n idiv sizeof (type) == n xor dx,dx mov ax,ptr1 sub ax,ptr2 sbb dx,0 ; carry extend mov bx,n idiv For the most common (2^n, 2*n) cases, this takes exactly as many bytes and is just as fast as the wrong code. The general case is just 3 extra bytes (and won't occur with word alignment). This kind of thing is very common (and very maddening) in system code. I have yet to see a 16-bit system that didn't break at some 32K boundary because of signed/unsigned carelessness. The bottom line is that my 16-bit programs designed to use 40K of buffers have to get by with 30K until I can track down all the compiler/system bugs and find work arounds. BTW, 32-bit machines often mess it up also - they get by with it because 2G arrays aren't very common. P.S. - beware the fateful number 32767 when writing code for 16-bit systems . . . -- Stuart D. Gathman <..!{vrdxhq|daitc}!bms-at!stuart>