北京中御建设公司网站wordpress getthememod
文章目录
- 编译时校验
 - 功能描述
 - 代码实现
 - 示例代码
 - 正常编译示例
 - 编译错误示例
 - 预处理之后的结果
 
- 代码解析
 - `!!e`
 - `struct {int:-!!(e); }`
 - `sizeof(struct {int:-!!(e); })`
 
- 参考代码
 
编译时校验
功能描述
用于在编译时检查一个条件是否为真,如果条件为真则会编译失败,编译器报错
反之如果条件为假,则编译正常,且有返回值,返回 0。
代码实现
/** Force a compilation error if condition is true, but also produce a* result (of value 0 and type int), 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) ((int)(sizeof(struct { int:(-!!(e)); })))
 
参数 e 表示用于判断的表达式
示例代码
正常编译示例
#include <stdio.h>#define BUILD_BUG_ON_ZERO(e) ((int)(sizeof(struct { int:(-!!(e)); })))int main(void)
{printf("Compilation successful %d.\n", BUILD_BUG_ON_ZERO(0));return 0;
}
 
结果打印
Compilation successful 0.
 
编译错误示例
#include <stdio.h>#define BUILD_BUG_ON_ZERO(e) ((int)(sizeof(struct { int:(-!!(e)); })))int main(void)
{printf("Compilation successful %d.\n", BUILD_BUG_ON_ZERO(1));return 0;
}
 
编译错误信息
test.c: In function ‘main’:
test.c:3:51: error: negative width in bit-field ‘<anonymous>’3 | #define BUILD_BUG_ON_ZERO(e) ((int)(sizeof(struct { int:(-!!(e)); })))|                                                   ^
test.c:7:44: note: in expansion of macro ‘BUILD_BUG_ON_ZERO’7 |     printf("Compilation successful %d.\n", BUILD_BUG_ON_ZERO(1));
 
预处理之后的结果
gcc -E test.c -> test.i
 
int main(void)
{printf("Compilation successful %d.\n", ((int)(sizeof(struct { int:(-!!(1)); }))));return 0;
}
 
代码解析
!!e
 
对条件 e 进行两次逻辑非运算,得到 逻辑值 结果 0 或者 1。如果表达式 e 的结果为 0 ,则得到 0 , 如果为非 0 值,则得到 1 。
struct {int:-!!(e); }
 
如果表达式 e 的结果为 0,则得到结构体 struct {int:0;},这是一个匿名的位域结构体,位域宽度为 0。
如果表达式 e 的结果为 1,则得到结构体 struct {int:-1;},则编译错误。由于位域的宽度不能是负的,所以编译错误,提示错误 error: negative width in bit-field <anonymous>。
sizeof(struct {int:-!!(e); })
 
如果表达式 e 的结果为 0,则使用 sizeof 运算符计算得到这个匿名结构体 struct {int:0;} 的大小为 0,宏的返回值为 0。
参考代码
- https://blog.csdn.net/u012028275/article/details/127478561
 
