C语言——断言,调试技巧
1.断言assert(_Expression)是一个宏,在<assert.h>中定义
2.用法
断言可以方便调试
#include <assert.h>
int main(void){
int a = 1;
assert(a == 0);
return 0;
}
可以看到,当表达式为假(或者值为0),断言就会触发。
3.关闭断言
在<assert.h>中,有这样的代码
#ifdef NDEBUG
#define assert(_Expression) ((void)0)
可以看到,如果定义了宏NDEBUG,就会关闭断言
所以当调试之后,使用#define NDEBUG就可以关闭断言
define一定要放在include <assert.h>之前,否则就不会满足条件编译(编译之后才定义了DEBUG,这样就不能关闭了)
#define NDEBUG
#include <assert.h>
int main(void){
int a = 1;
assert(a == 0);
return 0;
}