C语言之assert()篇

assert宏的原型定义在<assert.h>中,其作用是如果它的条件返回错误,则终止程序执行,原型定义:

#include <assert.h>
void assert( int expression );

assert的作用是现计算表达式 expression ,如果其值为假,那么它先向stderr打印一条出错信息,然后通过调用 abort 来终止程序运行

试看如下代码:

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


int main()
{
       FILE *fp;
    
       fp = fopen( "test.txt", "w" );//以可写的方式打开一个文件,如果不存在就创建一个同名文件
       assert( fp );    //所以这里不会出错
       fclose( fp );
    
       fp = fopen( "noexitfile.txt", "r" );//以只读的方式打开一个文件,如果不存在就打开文件失败
       assert( fp );//所以这里出错
       fclose( fp );//程序永远都执行不到这里来
       return 0;
}

缺点:频繁的调用会极大的影响程序的性能,增加额外的开销。

程序中关键的地方可以通过assert这个宏来断言。如果断言非真,程序停止,标准错误输出一条具体的错误信息。

在实战中,程序直接停止是很不好的现象,因此断言只在调试程序使用。

————————————————————————————————————————————————————————

(1)NDEBUG宏

#include <stdio.h>
#define NDEBUG
#include <assert.h>

int main()
{
    int i = 0;
    assert(i == 0);
    print("assert不会起作用")

    return 0;
}

(2)打开断言

#undef NDEBUG
#include<assert.h>
#include <stdio.h>
#undef NDEBUG
#include <assert.h>


void func1()
{
    int i = 0;

    assert(i == 0);
    assert(i == 1);
}

int main()
{
    func1();
    printf("hello world\n");
    return 0;
}

输入结果:

(3)关闭断言

#define NDEBUG
#include<assert.h>
#include <stdio.h>
#define NDEBUG
#include <assert.h>


void func2()
{
    int i = 0;

    assert(i == 0);
    assert(i == 1);
}

int main()
{
    func2();
    printf("hello world\n");
    return 0;
}

输出结果:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值