strcmp

Chris Torek torek at elf.ee.lbl.gov
Wed Jun 19 04:54:42 AEST 1991


>In article <1991Jun18.074029.12226 at panix.uucp>
>yanek at panix.uucp (Yanek Martinson) writes:
>>For strcmp(s,t): while(*s++==*t++&&*s&&*t); return *s-*t;

In article <1991Jun18.153653.1494 at zoo.toronto.edu> henry at 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 at ee.lbl.gov



More information about the Comp.lang.c mailing list