C++ ASSERT

黎 浩然/ 14 5 月, 2022/ C/C++, 计算机/COMPUTER/ 0 comments

assert宏的原型定义在 <assert.h>。其作用是如果它的条件返回错误,则终止程序执行!可以通过定义 NDEBUG 来关闭 assert,但是需要在源代码的开头,include <assert.h> 之前。

void assert(int expression);
#include <stdio.h>
#include <assert.h>
int main() {
int x = 7;
    /*  Some big code in between and let's say x
    is accidentally changed to 9  */
    x = 9;
    // Programmer assumes x to be 7 in rest of the code
    assert(x==7);
    /* Rest of the code */
    return 0; 
}
//assert: assert.c:13: main: Assertion 'x==7' failed.

可以看到输出会把源码文件,行号错误位置,提示出来!

/**
* @file ignore_assert.c * @brief 忽略断言
* @author Ernest
* @version v1
* @date 2019-07-25
*/
# define NDEBUG // 忽略断言 #include<assert.h>
int main(){
    int x=7;
    assert(x==5);
    return 0; 
}

忽略断言的方式如上。

Share this Post

Leave a Comment

您的邮箱地址不会被公开。 必填项已用 * 标注

*
*