Idiomatic way to check for empty string in C?

In the current codebase I look there for at least the following:

  • if(strlen(str) == 0)

  • if(str[0] != 0)

  • if(!*str)

And similar options are empty / not empty for him. The former reads better, but may be time-wasting (which may not matter). And I suppose it is possible to make a macro #define STR_EMPTY(str) (*(str) == 0)

.

But anyway, is there a generally accepted way to check if a string is not in C?

+3


source to share


5 answers


Not. I saw all three. I personally use

if (!str[0])

      



Using strlen is a waste of cpu time and unsafe if you cannot guarantee that the string is complete.

+4


source


  • if(strlen(str) == 0)

    -> it will crash if str==NULL

    (you need to test it before using strlen

    )
  • if(str[0] != 0)

    → same as above
  • if(!*str)

    -> this actually does the same as 2)

To summarize: if you want to do it safely:



if(!str || !(*str)) { /* empty string or NULL */ }

      

+3


source


If you already know that str

doesn't matter:

if (!*str) {
    // empty string
}

      

Otherwise:

if (!str || !*str) {
    // empty string
}

      

Forget about strlen()

.

+1


source


All of your examples are fine. This should be clear from the fact that all three are in your codebase that there is no "generally accepted" method.

0


source


I would definitely go with strlen(str) == 0

, just for clarity.

The function should be implemented something like this:

int strlen(char *s) {
  int len = 0;
  while(*(s++)) len++;
  return len;
}

      

so there won't be much overhead.

Edit: assuming you're sure that the string is actually null terminated.

0


source







All Articles