C语言标准库之 <assert.h>

在 C 语言的标准库 <assert.h> 中主要定义了一个宏函数 void assert (int expression); ,当函数的参数 expression 的值为 0 时,assert() 函数将会把调用 assert(expression); 语句所在的文件名、行号和 expression 等信息一起输出到标准输出流中,并调用 C 的 abort() 系统调用方法中止程序的执行,让程序员知道程序在这个地方出错了。因此,assert() 函数是专门为 debug 准备的:

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

int main()
{
    int a = 12, b = 24;
    assert(a > b);
    printf("a is larger than b!\n");

    return 0;
}

上述程序的输出如下所示:

Assertion failed: a > b, file G:\CLibLearning\main.c, line 9

此处,printf 语句将不再执行,因为运行到 assert 语句时程序就已经被中止退出。

当 debug 阶段已经全部结束时,不需要逐一把源代码中的调用 assert 的语句去掉,只需要#include <assert.h> 语句前添加宏 #define NDEBUG 即可以使得所有的 assert() 语句都失效:

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

#define NDEBUG

#include <assert.h>


int main()
{
    int a = 12, b = 24;
    assert(a > b);
    printf("a is larger than b!\n");

    return 0;
}

上述程序将输出:

a is larger than b!
  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值