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
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 to share