Double Negation in C++

后端 未结 14 2889
你的背包
你的背包 2020-11-22 10:40

I just came onto a project with a pretty huge code base.

I\'m mostly dealing with C++ and a lot of the code they write uses double negation for their boolean logic.

14条回答
  •  爱一瞬间的悲伤
    2020-11-22 11:11

    It's actually a very useful idiom in some contexts. Take these macros (example from the Linux kernel). For GCC, they're implemented as follows:

    #define likely(cond)   (__builtin_expect(!!(cond), 1))
    #define unlikely(cond) (__builtin_expect(!!(cond), 0))
    

    Why do they have to do this? GCC's __builtin_expect treats its parameters as long and not bool, so there needs to be some form of conversion. Since they don't know what cond is when they're writing those macros, it is most general to simply use the !! idiom.

    They could probably do the same thing by comparing against 0, but in my opinion, it's actually more straightforward to do the double-negation, since that's the closest to a cast-to-bool that C has.

    This code can be used in C++ as well... it's a lowest-common-denominator thing. If possible, do what works in both C and C++.

提交回复
热议问题