Is !! a safe way to convert to bool in C++?

后端 未结 17 1722
醉梦人生
醉梦人生 2020-11-29 22:25

[This question is related to but not the same as this one.]

If I try to use values of certain types as boolean expressions, I get a warning. Rather than su

相关标签:
17条回答
  • 2020-11-29 22:37

    Careful!

    • A boolean is about truth and falseness.
    • An integer is about whole numbers.

    Those are very distinct concepts:

    • Truth and falseness is about deciding stuff.
    • Numbers are about counting stuff.

    When bridging those concepts, it should be done explicitly. I like Dima's version best:

    b = (t != 0);

    That code clearly says: Compare two numbers and store the truth-value in a boolean.

    0 讨论(0)
  • 2020-11-29 22:38

    If you're worried about the warning, you can also force the cast: bool b = (bool)t;

    0 讨论(0)
  • 2020-11-29 22:40

    Comparison to 0 doesn't work so well. Which comes back -- why !! vs. ternary?

    class foo { public: explicit operator bool () ; };
    
    foo f;
    
    auto a = f != 0; // invalid operands to binary expression ('foo' and 'int')
    auto b = f ? true : false; // ok
    auto c = !!f; // ok
    
    0 讨论(0)
  • 2020-11-29 22:40

    I would use bool b = t and leave the compile warning in, commenting on this particular line's safety. Disabling the warning may bite you in the butt in another part of the code.

    0 讨论(0)
  • 2020-11-29 22:41

    The double not feels funny to me and in debug code will be very different than in optimized code.

    If you're in love with !! you could always Macro it.

    #define LONGTOBOOL(x) (!!(x))
    

    (as an aside, the ternary operator is what I favor in these cases)

    0 讨论(0)
  • 2020-11-29 22:42

    I would not use:

    bool b = !!t;
    

    That is the least readable way (and thus the hardest to maintain)

    The others depend on the situation.
    If you are converting to use in a bool expression only.

    bool b = t ? true : false;
    if (b)
    {
        doSomething();
    }
    

    Then I would let the language do it for you:

    if (t)
    {
        doSomething();
    }
    

    If you are actually storing a boolean value. Then first I would wonder why you have a long in the first places that requires the cast. Assuming you need the long and the bool value I would consider all the following depending on the situation.

    bool  b = t ? true : false;      // Short and too the point.
                                     // But not everybody groks this especially beginners.
    bool  b = (t != 0);              // Gives the exact meaning of what you want to do.
    bool  b = static_cast<bool>(t);  // Implies that t has no semantic meaning
                                     // except as a bool in this context.
    

    Summary: Use what provides the most meaning for the context you are in.
    Try and make it obvious what you are doing

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