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

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

    !! is only useful when you're using a boolean expression in arithmetic fashion, e.g.:

    c = 3 + !!extra; //3 or 4
    

    (Whose style is a different discussion.) When all you need is a boolean expression, the !! is redundant. Writing

    bool b = !!extra;
    

    makes as much sense as:

    if (!!extra) { ... }
    
    0 讨论(0)
  • 2020-11-29 22:45

    I recommend to use

    if (x != 0)

    or

    if (x != NULL)

    instead of if(x); it's more understandable and readable.

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

    Alternatively, you can do this: bool b = (t != 0)

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

    I would use b = (0 != t) -- at least any sane person can read it easily. If I would see double dang in the code, I would be pretty much surprised.

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

    I recommend never suppressing that warning, and never using a c cast (bool) to suppress it. The conversions may not always be called as you assume.

    There is a difference between an expression that evaluates to true and a boolean of that value.

    Both !! and ternary take getting used to, but will do the job similarly, if you do not want to define internal types with overloaded casts to bool.

    Dima's approach is fine too, since it assigns the value of an expression to a bool.

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

    The argument of the ! operator and the first argument of the ternary operator are both implicitly converted to bool, so !! and ?: are IMO silly redundant decorations of the cast. I vote for

    b = (t != 0);
    

    No implicit conversions.

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