"str*cmp()" ain't Boolean (was Re: v18i058: mush - Mail User's Shell, Part01/22)
Bill Carpenter
wjc at hos1cad.ATT.COM
Sun May 5 04:17:18 AEST 1991
guy> Perhaps this is a hint that one shouldn't treat "strncmp()" as if
guy> it were a Boolean function, and should instead compare its result
guy> with 0 explicitly, e.g. if you're comparing strings for equality,
guy> use "=="?
Since most of the time I'm using str*cmp() in a Boolean way anyhow,
and since I used to frequently get the sense of the test reversed, I
almost always do it as a macro now:
#define EQSTR(a,b) ((a) && (b) && (*(a) == *(b)) && !strcmp((a),(b)))
#define EQSTRN(a,b,n) ((a) && (b) && (*(a) == *(b)) && !strncmp((a),(b),(n)))
Of course, these are a little elaborate and have side-effects, so you
could stick with the simpler
#define EQSTR(a,b) (!strcmp((a),(b)))
#define EQSTRN(a,b,n) (!strncmp((a),(b),(n)))
(especially if you enjoy dereferenced nulls as much as I do :-).
--
Bill Carpenter att!hos1cad!wjc or attmail!bill
More information about the Comp.lang.c
mailing list