Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic way of checking for an empty string in C?

Tags:

c

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 ?

like image 222
user1255770 Avatar asked Oct 29 '25 10:10

user1255770


2 Answers

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.

like image 181
Carey Gregory Avatar answered Oct 31 '25 00:10

Carey Gregory


  1. if(strlen(str) == 0) -> it will crash if str==NULL (you need to check it before you use strlen)
  2. if(str[0] != 0) -> the same as above
  3. if(!*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 */ }
like image 25
sirgeorge Avatar answered Oct 31 '25 00:10

sirgeorge



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!