Nov 25, 2009

The right way to check whether the C string is empty

It is:
char *s;
// .. do something with s ...
if (!*s) printf("empty!\n");
or
if (0 == *s) printf("empty!\n");
I prefer the second one, because find it easier to read, but it doesn't matter really.

The most popular bad ways to do this:
  • if (0 == strlen(s)) printf("empty\n");
  • if (0 == strcmp(s, "")) printf("OMG, empty!\n");
And it is not a joke, today I saw 2 independent reviews with such kind of stuff.

p.s. There is a popular joke about how foreign developers check bool value to be a true:
if (4 == strlen(bool2str(value))) printf("its true!\n");

No comments:

Post a Comment