c/c++ assert宏用法

本文介绍了C/C++中的assert宏用于参数合法性检查,当条件不满足时,程序会终止并提供错误信息,便于快速定位错误。通过示例展示了在不同环境下assert宏的行为,并提醒在产品发布时应禁用assert以避免影响程序运行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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宏失效;

 




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值