c/c++ assert宏用法

来源:互联网 发布:unity3d往复运动 编辑:程序博客网 时间:2024/04/29 06:25

assert用途:检测参数的合法性,当条件为真时,程序继续往下执行,当条件为假时,终端打印错误提示信息,程序并终止,主要是为了方便程序员调试及快速查错,从错误提示信息中能很快定位错误发生的位置,从而快速找到问题所在。


格式:   assert(条件表达式)


举例:

#ifndef NDEBUG
#define NDEBUG              //让程序中所有assert断言失效,必须放在#include <assert.h>语句之前,在产品开发与测试阶段此宏不需定义
#endif

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h> 

void PassNullValue(char *pStr)
{
    assert(pStr != NULL);   //条件为真时,程序继续往下执行,条件为假时
                                              //终端打印具体错误提示信息
    printf("pStr's value: %s\n",pStr);
    strcat(pStr,"NULL");
    return;
}


int main(int argc, char *argv[])
{
    char *pNull=NULL;
    printf("assert test start...\n");
    PassNullValue(pNull);
    printf("program test end!\n");
    return 0;
}

运行结果:

--------没定义NDEBUG宏情况下:

[root@linux189 test]# ./TestAssert
assert test start...
TestAssert: TestAssert.cpp:16: void PassNullValue(char*): Assertion `pStr != __null' failed.
已放弃

 

--------在#include <assert.h>包含语句之前定义了NDEBUG宏情况下:

[root@linux189 test]# ./TestAssert
assert test start...
pStr's value: (null)
段错误

注意事项:产品发布版本需要在#include <assert.h>语句之前加上NDEBUG宏的定义,以使所有assert宏失效;