assert

定义于头文件 <cassert>
#ifdef NDEBUG

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

#endif

assert 的定义依赖于标准库不定义的另一个宏 NDEBUG

NDEBUG 在包含了 <cassert> 的源代码中的一点定义为宏名,则 assert 不做任何事。

若不定义 NDEBUG ,则 assert 将其参数(必须拥有标量类型)与零比较相等。若相等,则 assert 在标准错误输出上输出实现指定的诊断信息,并调用 std::abort 。诊断信息要求包含 expression 的文本,还有标准宏 __FILE____LINE__ 以及标准变量 __func__ 的值。

表达式 assert(E) 保证为常量子表达式,若下列之一成立

  • 在最后定义或重定义(即包含了头文件 <cassert><assert.h>assert 位置定义了 NDEBUG;或
  • E 按语境转换成 bool 后,是求值为 true 的常量子表达式。
(C++17 起)

目录

参数

condition - 标量类型的表达式

返回值

(无)

注意

因为 assert 是一个类函数宏,在 condition 中未被括号保护的逗号都被转译成宏参数的分隔符。这种逗号在模板参数列表中常能找到:

assert(std::is_same_v<int, int>); // 错误: assert 不接收二个参数
assert((std::is_same_v<int, int>)); // OK :一个参数
static_assert(std::is_same_v<int, int>); // OK :非宏

示例

#include <iostream>
// 去注释化则禁用 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

参阅

静态断言 进行编译时断言检查 (C++11 起)
导致异常程序终止(不清理)
(函数)
assertC 文档

版本历史

  • (当前 | 先前 2017年6月6日 (二) 18:29Fruderica讨论 | 贡献. . (2,389字节) (-84). . (撤销)
  • 当前 | 先前 2014年10月26日 (日) 17:43P12bot讨论 | 贡献 . . (2,473字节) (0). . (Fix some translations) (撤销)
  • 当前 | 先前 2013年7月2日 (二) 09:01P12bot讨论 | 贡献 . . (2,473字节) (-64). . (Use {{lc}}. Update links. Various fixes.) (撤销)
  • 当前 | 先前 2012年11月2日 (五) 17:00P12bot讨论 | 贡献 . . (2,537字节) (+96). . (r2.7.3) (机器人添加:de, en, it, pt, ru 去除:zh) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 11:35P12讨论 | 贡献 . . (2,441字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 07:00TranslationBot讨论 | 贡献. . (2,441字节) (-52). . (Translated from the English version using Google Translate) (撤销)
  • 当前 | 先前 2012年10月25日 (四) 14:24P12讨论 | 贡献 . . (2,493字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前 2012年10月25日 (四) 13:00TranslationBot讨论 | 贡献. . (2,493字节) (+2,057). . (Translated from the English version using Google Translate) (撤销)
  • 当前 | 先前 2012年5月4日 (五) 14:08P12bot讨论 | 贡献 . . (436字节) (+97). . (r2.7.3) (机器人添加:en, es, fr, ja) (撤销)
  • 当前 | 先前 2012年5月1日 (二) 04:37P12讨论 | 贡献 . . (339字节) (0). . (1个修订: Import from Dokuwiki) (撤销)
  • 当前 | 先前) 2012年5月1日 (二) 04:37P12讨论 | 贡献. . (339字节) (+339). . (Import from dokuwiki)