Implicit String Conversions to Booleans -- Sandor Dargo

SANDOR_DARGO_ROUND.JPGIn this article, we'll learn about -Wstring-conversion, something I learned from C++ Brain Teasers by Anders Schau Knatten](https://www.sandordargo.com/blog/2024/10/16/cpp-brain-teasers). Clang offers this compiler warning which fires on implicit conversions from C-strings to bools.

Implicit String Conversions to Booleans

by Sandor Dargo

From the article:

Let’s start with the first part by explaining why such an implicit conversion is possible. A string literal is an array of const chars. Arrays can be converted into pointers, something we talked about last week when we discussed why spans are so useful. This is also called decay. Furthermore, pointers can be converted into booleans. That is how a string literal can be converted into a bool.

static_assert(!!"" == true);
static_assert(static_cast<bool>("") == true);

What might be surprising though is that even an empty string literal is converted into true. The reason is that only a nullptr would be converted into false, but an empty string literal is an array of a size of one so it’s not a nullptr. As a result, "" converted to true. The possible confusion is that the one character in that array of one is the \0 terminator. But this shouldn’t really matter. You shouldn’t use such shady implicit conversions.

We could end this article right here. But life is not ideal and I tried to turn on -Wstring-conversion in a production codebase where I found a few different cases of string literals conversions.

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.