C++系统学习之C库assert

C库之

assert.h定义了一个作为标准调试工具的宏

宏函数

函数

说明

assert

Evaluate assertion (macro)

assert

当使用assert()里,给它一个参数,即一个表示断言为真的表达式。预处理器产生测试该断言的代码。如果断言不为真,则发出一个错误信息告诉断言是什么以及的失败之后,程序会终止。下面是一个例子:

#include <cstdio>
#ifndef NDEBUG
#include <cassert>
#endif // NDEBUG

void cout_number(int * num)
{
#ifndef NDEBUG
    assert(num != NULL);
#endif // NDEBUG
    printf("%d\n", *num);
}

int main(int argc, const char **argv)
{
    int a = 100;
    int *b = NULL;
    int *c = NULL;

    b = &a;

    cout_number(b);
    cout_number(c); // Fails

    return 0;
}

当产生断言时会出现下面这种格式:

Assertion failed: expression, file filename, line line number 

这个宏是用来铺获编程错误,而不是用户或运行时错误,因此它通常是禁用程序退出后的调试阶段。

评论

暂无评论