我在/usr/include/linux/kernel.h中碰到了这个奇怪的宏代码:
/* Force a compilation error if condition is true, but also produce a
result (of value 0 and type size_t), so the expression can be used
e.g. in a structure initializer (or where-ever else comma expressions
aren't permitted). */
#define BUILD_BUG_ON_ZERO(e) (sizeof(struct { int:-!!(e); }))
#define BUILD_BUG_ON_NULL(e) ((void *)sizeof(struct { int:-!!(e); }))
Run Code Online (Sandbox Code Playgroud)
怎么:-!!办?
我刚刚进入一个拥有相当庞大代码库的项目.
我主要处理C++,他们编写的很多代码都使用布尔逻辑的双重否定.
if (!!variable && (!!api.lookup("some-string"))) {
do_some_stuff();
}
Run Code Online (Sandbox Code Playgroud)
我知道这些人都是聪明的程序员,很明显他们不会偶然这样做.
我不是经验丰富的C++专家,我唯一猜测他们这样做的原因是他们想要绝对肯定被评估的值是实际的布尔表示.所以他们否定它,然后再次否定它以使其恢复到它的实际布尔值.
这是正确的,还是我错过了什么?
我遇到了以下代码段:
pt->aa[!!(ts->flags & MASK)] = -val;
Run Code Online (Sandbox Code Playgroud)
!!(双惊叹号/感叹号/两个非操作符)代表c?(!!NULL) == NULL吗?我经常看到有经验的程序员写!!x,即使预期的表达式是布尔值(即零或非零)而不是整数。
例如,来自 boost 的一行:
BOOST_ASSERT(!!p); // where `p` is a pointer
Run Code Online (Sandbox Code Playgroud)
什么!!p时候才p做呢?
我对布尔参数的理解是将表达式转换为整数类型的值,并将该值与零、显式或隐式(使用if或其三元运算符等效)进行比较。
因此,如果我对 Boolean 的理解是正确的,那么任何需要 Boolean 并且只期望0或被1错误实现的东西。
澄清一下:很明显,!转换为bool; 问题是明确询问为什么。