问题描述
实际上,这是。
宏有点名不副实;它应该更像BUILD_BUG_OR_ZERO
,而不是...ON_ZERO
. (。)
您应该像这样阅读表达式:
sizeof(struct { int: -!!(e); }))
-
(e)
: 计算表达式e
。 -
!!(e)
: 逻辑否定两次:0
ife == 0
; 否则1
。 -
-!!(e)
: 数值否定步骤 2 中的表达式:0
如果它是0
; 否则-1
。 -
struct{int: -!!(0);} --> struct{int: 0;}
:如果它是零,那么我们声明一个具有宽度为零的匿名整数位域的结构。一切都很好,我们照常进行。 -
struct{int: -!!(1);} --> struct{int: -1;}
: 另一方面,如果它不为零,那么它将是一个负数。用负宽度声明任何位域都是编译错误。
所以我们要么在结构中得到一个宽度为 0 的位域,这很好,要么是一个宽度为负的位域,这是一个编译错误。然后我们取sizeof
那个字段,所以我们得到一个size_t
具有适当宽度的 a(在 0 的情况下将e
是 0)。
有人问:
在这里得到了很好的回应:
这些宏实现了编译时测试,而 assert() 是运行时测试。
非常正确。您不希望在运行时检测内核中可能更早发现的问题!它是操作系统的关键部分。在编译时可以检测到任何程度的问题,那就更好了。
解决方法
/* 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); }))
做什么:-!!
?