电商网站建设开发,seo网站结构,王也手机壁纸,做网站创新互联文章目录 编译时校验功能描述代码实现示例代码正常编译示例编译错误示例预处理之后的结果 代码解析!!estruct {int:-!!(e); }sizeof(struct {int:-!!(e); }) 参考代码 编译时校验
功能描述
用于在编译时检查一个条件是否为真#xff0c;如果条件为真则会编译失败#xff0c… 文章目录 编译时校验功能描述代码实现示例代码正常编译示例编译错误示例预处理之后的结果 代码解析!!estruct {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* arent 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.iint 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