【发布时间】:2012-03-03 00:42:53
【问题描述】:
我在/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); }))
:-!! 是做什么的?
【问题讨论】:
-
- 一元减号
!逻辑非
与给定的整数 e 不相反,因此变量可以是 0 或 1。 -
git blame 告诉我们这种特殊形式的静态断言是introduced by Jan Beulich in 8c87df4。显然他有充分的理由这样做(参见提交信息)。
-
几乎不用说创建的位域是匿名的。这与 C++ 模板元编程的精神相同,即在编译时发生的事情可以在编译时检查。
-
等等,我以为
sizeof的参数没有被评估。在这种情况下是错的吗?如果是这样,为什么?因为它是一个宏? -
@cpcloud,
sizeof确实“评估”类型,而不是值。在这种情况下,它的类型无效。
标签: c linux macros linux-kernel