1、assert的作用
int i = 0;
assert(i == 0);
printf("hello_world\n");
当括号中的表达式为 true时,程序继续执行下一条语句。
当括号中的表达式为false,程序将直接终止运行,并输出相应信息,如终止所在行等。
2、取消assert的功能
assert函数一般用在代码调试,在程序真正运行时并不希望总是出现程序异常终止的现象。
#define NDEBUG
#include <assert.h>
这两条语句结合使用即可取消 assert的终止,而不需要注释掉代码。
3、恢复assert的功能
#undef NDEBUG
#include <assert.h>
在使用 2中的代码取消 assert的作用后,可以使用上面的代码恢复其功能。
这两条语句只对其后面的assert有效果,对前面的无效。
4、示例代码片
#define NDEBUG
#include
#include
void func1()
{
int i = 0;
assert(i == 0);
printf("%d\n",i);
i++;
assert(i == 0);//define NDEBUG cannot abort
printf("%d\n",i);
}
#undef NDEBUG
#include
void func2()
{
int i = 0;
assert(i == 0);
printf("%d\n",i);
i++;
assert(i == 0);//undef NDEBUG should abort
printf("%d\n",i);
}
int main(int argc,char *argv[])
{
if(argc < 2)
return 0;
if(argv[1][0] == '1')
func1();
else if(argv[1][0] == '2')
func2();
return 0;
}