strcmp

Henry Spencer henry at zoo.toronto.edu
Wed Jun 19 01:36:53 AEST 1991


In article <1991Jun18.074029.12226 at panix.uucp> yanek at panix.uucp (Yanek Martinson) writes:
>For intcmp(a,b) why not just use a-b ? That will tell you if they are equal
>and if not, which is greater.

If the subtraction doesn't overflow, that is.  (The effects of overflow
are undefined, and strange things can happen even with old compilers.)

>For strcmp(s,t): while(*s++==*t++&&*s&&*t); return *s-*t;

Apart from being inefficient, this code is wrong, since the final comparison
must be done as if characters are unsigned.  (This is not precisely the rule
I would have picked, but at least ANSI C did pick something specific...)
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...
-- 
"We're thinking about upgrading from    | Henry Spencer @ U of Toronto Zoology
SunOS 4.1.1 to SunOS 3.5."              |  henry at zoo.toronto.edu  utzoo!henry



More information about the Comp.lang.c mailing list