在线文档教程
C++
应用 | Utilities

assert

断言

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

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

如果NDEBUG被定义为源代码中<cassert>则包括在内。assert什么都不做。

如果NDEBUG则未定义assert检查其参数%28(必须具有标量类型%29)是否等于零。如果是的话,assert输出实现-标准错误输出和调用的特定诊断信息std::abort.诊断资料须包括expression,以及标准宏的值。__FILE__,,,__LINE__,以及标准变量__func__...

The expression assert(E) is guaranteed to be a constant subexpression, if either. NDEBUG is defined at the point where assert is last defined or redefined (i.e., where the header or was last included or E, contextually converted to bool, is a constant subexpression that evaluates to true.(since C++17)

  • NDEBUG定义为assert是最后定义或重新定义的%28i。e.,其中的标题<cassert>或<assert.h>最后包括%29;或

  • E,上下文转换为bool,是一个常数子表达式,其计算值为true...

%28自C++17%29

参数

condition-expression of scalar type

返回值

%280%29

注记

因为assert是类函数宏,在不受括号保护的情况下,任何逗号都被解释为宏参数分隔符。这些逗号经常出现在模板参数列表中:

二次

assert(std::is_same_v<int, int> // error: assert does not take two arguments assert((std::is_same_v<int, int>) // OK: one argument static_assert(std::is_same_v<int, int> // OK: not a macro

二次

二次

#include <iostream> // uncomment to disable assert() // #define NDEBUG #include <cassert> int main() { assert(2+2==4 std::cout << "Execution continues past the first assert\n"; assert(2+2==5 std::cout << "Execution continues past the second assert\n"; }

二次

可能的产出:

二次

Execution continues past the first assert test: test.cc:10: int main(): Assertion `2+2==5' failed. Aborted

二次

另见

static assertionperforms compile-time assertion checking (since C++11)
abortcauses abnormal program termination (without cleaning up) (function)

c索赔文件

© cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

http://en.cpPreference.com/w/cpp/Error/ASSERT