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

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

    Disable the warning.

    Write for clarity first; then profile; then optimize for speed, where required.

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

    All valid techniques, all will generate the same code.

    Personally, I just disable the warning so I can use the cleanest syntax. Casting to a bool is not something I'm worried about doing accidentally.

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

    !! may be compact, but I think it is unnecessarily complicated. Better to disable the warning or use the ternary operator, in my opinion.

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


    Yes it is safe.


    0 is interpreted as false, everthing else is true,
    hence !5 comes out as a false
    !0 comes out as true
    so !!5 comes out as true

    0 讨论(0)
  • 2020-11-29 23:01

    I really hate !!t!!!!!!. It smacks of the worst thing about C and C++, the temptation to be too clever by half with your syntax.

    bool b(t != 0); // Is the best way IMHO, it explicitly shows what is happening.

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