Comparing strings...
Paul John Falstad
pfalstad at drops.Princeton.EDU
Mon Oct 15 07:45:37 AEST 1990
In article <11486 at alice.att.com> ark at alice.att.com (Andrew Koenig) writes:
>In article <3330 at idunno.Princeton.EDU>, pfalstad at phoenix.Princeton.EDU (Paul John Falstad) writes:
>> int strcmp(char *s,char *t)
>> {
>> for (; *s && *s == *t; s++,t++);
>> return *s-*t;
>> }
>Whether or not this works depends on your definition of the problem.
>If you really want to follow the normal lexical convention that
>the null string compares <= anything else, and you're on a machine
>on which chars can be negative, then it doesn't work.
OK. Declare the chars unsigned then. (I copied this with minor changes
from K&R2, so I assumed it would be right.)
Other optimizations could be made:
int strcmp(char *s,char *t) /* declared register if you like */
{
unsigned char c,d;
while((c = (unsigned char) *s++) == (d == (unsigned char) *t++) && c);
return c-d;
}
I've heard of faster ways that take advantage of parallelism by
comparing a word or longword at a time. Can't remember if it was
worth it or not.
--
pfalstad at phoenix.princeton.edu The Germans are disputing it! Hegel is
arguing that the reality is merely an a priori adjunct of non-absolutistic
ethics; Kant, by the categorical imperative, is holding it ontologically
exists only in the imagination; and Marx is claiming it was off sides.
More information about the Comp.lang.c
mailing list