strcmp

Richard A. O'Keefe ok at goanna.cs.rmit.oz.au
Wed Jun 19 19:48:31 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;

Sorry, there's a mistake.  Let p = "\0followed by 50 million bytes of junk";
Then strcmp(p,p) will set s=p, t=p, find *s == *t == '\0', increment s and t,
and because the _next_ bytes aren't \0 it will keep going.  Not good.
In fact, if you call strcmp("\0a", "\0b") with that definition, it will
claim they _aren't_ equal, but they are both empty!

Keep it simple:
	while (*s == *t && *s != '\0' && *t != '\0')
	    s++, t++;
	return *s - *t;
Much as I hate to say this, a good compiler is likely to do just as well
from this as from anything cleverer.

-- 
Q:  What should I know about quicksort?   A:  That it is *slow*.
Q:  When should I use it?  A:  When you have only 256 words of main storage.



More information about the Comp.lang.c mailing list