In the current code base I'm looking at there's , at least, these:
if(strlen(str) == 0)if(str[0] != 0)if(!*str)And similar variants for it being empty/not empty . The first one reads better, but might waste time (which might nor might not matter). And I suppose one could make a #define STR_EMPTY(str) (*(str) == 0) macro.
But anyway, is there a commonly agreed upon way to check if a string is (not) empty in C ?
No. I've seen all three. Personally, I use
if (!str[0])
Using strlen is a waste of processor time and not safe unless you can guarantee the string is terminated.
if(strlen(str) == 0) -> it will crash if str==NULL (you need to check it before you use strlen)if(str[0] != 0) -> the same as aboveif(!*str) -> this is actually doing the same thing as 2) To summarise: if you want to do it safely:
if(!str || !(*str)) { /* empty string or NULL */ }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With