使用assert.h简介

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;
}
     
     
    
    
   
   

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值