December 9, 20241 yr 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â¬Ã¡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. View the full article
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.