Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!swrinde!sdd.hp.com!think.com!snorkelwacker.mit.edu!hsdndev!cmcl2!kramden.acf.nyu.edu!brnstnd From: brnstnd@kramden.acf.nyu.edu (Dan Bernstein) Newsgroups: comp.lang.c Subject: Re: strcmp Message-ID: <6476.Jun2023.30.3491@kramden.acf.nyu.edu> Date: 20 Jun 91 23:30:34 GMT References: <1991Jun18.153653.1494@zoo.toronto.edu> <14421@dog.ee.lbl.gov> <14498@dog.ee.lbl.gov> Organization: IR Lines: 29 In article <14498@dog.ee.lbl.gov> torek@elf.ee.lbl.gov (Chris Torek) writes: > > return (*(unsigned char *)--s1 - *(unsigned char *)s2); > >... this assumes that the subtraction will not overflow. > The word `overflow' is wrong. The subtraction cannot overflow. There > are several cases: [ discussion ] > Suppose, for instance, that char and int are both 16 > bits, and that we have two strings made up of characters (32761,0) > and (1,0) respectively. Wait a minute. First of all, if unsigned chars range from 0 to 65535, then subtracting two unsigned char values will give a range of -65535 to -1 for s1 < s2, 0 for s1 == s2, and 1 to 65535 for s1 > s2. There's no way these 131071 values can fit into a 16-bit int without further processing. On the other hand, how can sizeof(char) == sizeof(int)? I was under the impression that sizeof(char) had to be smaller than sizeof(int). Otherwise the getchar() interface explodes. If sizeof(char) < sizeof(int) and both are some number of bits, then the unsigned char subtraction will fit into int without overflow---provided you write it correctly: return ((int) (unsigned int) *(unsigned char *) --s1) - ((int) (unsigned int) *(unsigned char *) s2); This works, right? ---Dan