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

后端 未结 17 1929
醉梦人生
醉梦人生 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: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(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

提交回复
热议问题