-1

When I write bool x = "hallo", there is no error. It is assumed that the non-zero value is implicitly converted into a Boolean value, which represents the number 1:

#include <iostream>
using namespace std;

int main() {
    bool x = "hallo;
    cout << x << "\n";
    return 0;
}

But in other cases, there is an error, eg:

#include <iostream>
using namespace std;

int main() {
    string text = "hallo";
    bool x = text;
    cout << x << "\n";
    return 0;
}

Why is this different?

An error should not occur, because it is assumed that the text value is considered a non-zero value, so output should be 1.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770

1 Answers1

5

You are not seeing the behaviour that you think you are seeing. The content of the strings is not being tested.

In bool x="hallo";, "hallo" is not a std::string. It is a String Literal, a const array of chars of exactly the right length. Via array-to-pointer decay the address of the string literal can be used to initialize a boolean. Since the array cannot have a null address it will always be a non-zero value and always result in a boolean value of true regardless of the content of the string literal.

There is no implicit conversion between std::string and bool, so bool x=text; cannot compile.

user4581301
  • 33,082
  • 7
  • 33
  • 54
  • 1
    Side note: [A similar gotcha](https://godbolt.org/z/hhhToTqfa) Converting the string literal to a `bool` is preferred over the more intuitive `string`. – user4581301 Jul 14 '23 at 20:23