Automatic conversion from double/int/string to bool in C++

后端 未结 2 1549
终归单人心
终归单人心 2020-12-11 09:49

I\'m a Java programmer who has been trying to learn a bit of C++ on the side to expand on my knowledge. Here is a small code snippet which I think works due to impl

相关标签:
2条回答
  • 2020-12-11 10:30

    All base types can be converted to bool implicitly. Anything that is not 0 is TRUE, and 0 is FALSE.

    For user defined types, if you use pointers, anything that is not NULL is evaluates to TRUE, otherwise FALSE.

    If you use object instances and not pointers, you need to declare operator bool():

    class A
    {
    public:
       operator bool() {return false;};
    };
    
    //....
    
    A a;
    if ( a ) //compiles because of the operator
       //...;
    
    0 讨论(0)
  • 2020-12-11 10:36

    Pointers and integers, and also booleans, are integral types. The first three are all either pointers or integers, and since they are all non-zero, they convert to the boolean value true. The fourth value of type double converts to a zero integral value and hence false.

    Conversion of doubles that are not representable as integral values (like infinity and NaN) is undefined.

    See 4.9 for details, and also 4.12 for "Boolean conversions":

    A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true.

    Your 0.0 is an arithmetic type of zero value.

    Perhaps you may not be familiar with string literals in C++: "" denotes the array char[1] { 0 }, and this array (of one element) decays to a pointer to its first element, which is necessarily a non-null pointer. Similarly, "asdf" denotes an array char[5] { 'a', 's', 'd', 'f', 0 }, and again this decays to a (non-null) pointer to its first element. The actual value of the characters is entirely immaterial.

    0 讨论(0)
提交回复
热议问题