In 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 bool
s.
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 char
s. Arrays can be converted into pointers, something we talked about last week when we discussed whyspan
s 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 abool
.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 anullptr
would be converted intofalse
, but an empty string literal is an array of a size of one so it’s not anullptr
. As a result,""
converted totrue
. 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.