What is efficient way to test zero length string: `strlen(str) > 0` or `*str`

Viewed 190

Assuming char *str;, to test the empty string following approaches works

/* Approrach 1 */
if (str && strlen(str) > 0) {
    ... 
}

/* Approach 2 */
if (str && *str) {
    ...
}

What is the most preferable to use? I assume second will be faster as it does not have to iterate over the buffer to get the length. Also any downfalls of using the second?

5 Answers

I'll give a third option that I find would be better:

if (str && str[0]) {
    // ... 
}

The strlen method isn't ideal since it can iterate over a non-zero-length string. The compiler may optimize out that call entirely (as has been pointed out), but it won't on every compiler (and I assume the -ffreestanding option would disable this optimization), and it at least makes it look like more work needs to happen.

However, I consider the [0] to have much clearer intent than a *. I generally recommend using * when dereferencing a pointer to a single object, and using [0] when that pointer is to the first element of an array.


To be extra clear, you can do:

if (str && str[0] != '\0') {
    // ... 
}

but that starts tipping the special-to-alphanum-characters ratio towards hard-to-read.

Approach 2, because the first attempt will iterate over the string if it's not empty. And no, there are no downsides to approach 2.

What is the most preferable to use?

Obviously number one, as that is most readable.

I would ignore performance issues. Both CLANG and GCC will generate the same code for "-O3" options.

See godbolt

The first approach expresses programmer's intentions a bit more explicitly.

It's unlikely that the compiler would generate different code if you have optimization enabled. But if performance REALLY is an issue it's probably better to use the second approach. I say probably, because it's not 100% certain. Who knows what the optimizer will do? But there is a risk that the first approach will iterate over the whole string if it's not empty.

When it comes to readability, I'd say that the first is slightly more readable. However, using *str to test for an empty string is very idiomatic in C. Any seasoned C coder would instantly understand what it means. So TBH, the readability issue is mostly in case someone who is not a C programmer will read the code. If someone does not understand what if (str && *str) does, then you don't want them to modify the code either. ;)

If there is a coding standard for the code base you're working on, stick to that. If there's not, pick the one you like most. It does not really matter.

Related