Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!sun-barr!lll-winken!elroy.jpl.nasa.gov!usc!zaphod.mps.ohio-state.edu!caen!hellgate.utah.edu!dog.ee.lbl.gov!elf.ee.lbl.gov!torek From: torek@elf.ee.lbl.gov (Chris Torek) Newsgroups: comp.lang.c Subject: Re: strcmp Message-ID: <14421@dog.ee.lbl.gov> Date: 18 Jun 91 18:54:42 GMT References: <2695@m1.cs.man.ac.uk> <1991Jun18.074029.12226@panix.uucp> <1991Jun18.153653.1494@zoo.toronto.edu> Reply-To: torek@elf.ee.lbl.gov (Chris Torek) Organization: Lawrence Berkeley Laboratory, Berkeley Lines: 35 X-Local-Date: Tue, 18 Jun 91 11:54:42 PDT >In article <1991Jun18.074029.12226@panix.uucp> >yanek@panix.uucp (Yanek Martinson) writes: >>For strcmp(s,t): while(*s++==*t++&&*s&&*t); return *s-*t; In article <1991Jun18.153653.1494@zoo.toronto.edu> henry@zoo.toronto.edu (Henry Spencer) writes: >Apart from being inefficient, this code is wrong, since the final comparison >must be done as if characters are unsigned. ... That's aside from the fact >that the final comparison is being done on the two characters *after* the >mismatch rather than on the mismatch itself... ... which may not even exist (if the loop stopped on '\0'). The usual way to write strcmp, if one is not interested in working hard ---though one should be; a fast strcmp improves one's Dhrystone benchmarks, which as we all know is more important than speeding up real programs :-) ---is this: int strcmp(char *s1, char *s2) { /* * Loop until different, but stop if both are '\0'. */ while (*s1++ == *s2) if (*s2++ == '\0') return (0); /* * *--s1 and *s2 differ. One might be '\0'. */ return (*(unsigned char *)--s1 - *(unsigned char *)s2); } although this assumes that the subtraction will not overflow. -- In-Real-Life: Chris Torek, Lawrence Berkeley Lab CSE/EE (+1 415 486 5427) Berkeley, CA Domain: torek@ee.lbl.gov