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

后端 未结 17 1906
醉梦人生
醉梦人生 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) { ... }
    

提交回复
热议问题