首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

assert

在头文件<assert.h>中定义

?

?

#ifdef NDEBUG #define assert(condition)((void)0)#else #define assert(condition)/ * implementation defined * / #endif

?

?

宏的定义assert取决于另一个宏NDEBUG,它不是由标准库定义的。

如果NDEBUG在源代码中<assert.h>包含的位置被定义为宏名称,则不assert执行任何操作。

如果NDEBUG未定义,则assert检查其参数(必须具有标量类型)是否等于零。如果确实如此,则assert在标准错误输出和调用上输出实现特定的诊断信息abort()。诊断信息需要包括的文本expression,以及标准的宏的值__FILE____LINE__和预定义的变量__func__。(自C99以来)。

参数

条件

-

标量类型的表达

返回值

(none).

代码语言:javascript
复制
#include <stdio.h>
// uncomment to disable assert()
// #define NDEBUG
#include <assert.h>
#include <math.h>
 
int main(void)
{
    double x = -1.0;
    assert(x >= 0.0);
    printf("sqrt(x) = %f\n", sqrt(x));   
 
    return 0;
}

输出:

代码语言:javascript
复制
output with NDEBUG not defined:
a.out: main.cpp:10: main: Assertion `x >= 0.0' failed.
 
output with NDEBUG defined:
sqrt(x) = -nan

参考

  • C11标准(ISO/IEC 9899:2011):
    • 7.2.1.1断言宏(p:186-187)
  • C99标准(ISO / IEC 9899:1999):
    • 7.2.1.1断言宏(p:169)
  • C89 / C90标准(ISO/IEC 9899:1990):
    • 4.2.1.1断言宏

另请参阅

abort

导致程序异常终止(不清除)(功能)

| C++ documentation for assert |

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com