strcmp

Dan Bernstein brnstnd at kramden.acf.nyu.edu
Fri Jun 21 09:30:34 AEST 1991


In article <14498 at dog.ee.lbl.gov> torek at 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



More information about the Comp.lang.c mailing list