Double Negation in C++ code

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.

 if (!!variable && (!!api.lookup("some-string"))) {
       do_some_stuff();
 }                                   

I know these guys are intelligent programmers, it's obvious they aren't doing this by accident.

I'm no seasoned C++ expert, my only guess at why they are doing this is that they want to make absolutely positive that the value being evaluated is the actual boolean representation. So they negate it, then negate that again to get it back to its actual boolean value.

Is this a correct, or am I missing something?


这是一个转换为布尔的诀窍。


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++.


编码人员认为它会将操作数转换为布尔值,但由于&&的操作数已经隐含地转换为布尔值,所以它是完全多余的。

链接地址: http://www.djcxy.com/p/12770.html

上一篇: 实际使用零点

下一篇: C ++代码中的双重否定