断言是用于测试程序员所做假设的语句。例如,我们可以使用断言来检查 malloc() 返回的指针是否为 NULL。
以下是断言的语法。
如果表达式的计算结果为 0 (false),则表达式、源代码文件名和行号被发送到标准错误,然后调用 abort() 函数。
例如,考虑以下程序。
输出
上面的程序编译并运行良好。
在 Java 中,默认情况下不启用断言,我们必须将选项传递给运行时引擎以启用它们。
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;
}
Assertion failed: x==7, file test.cpp, line 13 This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information.断言与正常错误处理 断言主要用于检查逻辑上不可能的情况。例如,它们可用于检查代码在开始运行之前所期望的状态或在其完成运行之后的状态。与正常的错误处理不同,断言通常在运行时被禁用。因此,在 assert() 中编写可能导致副作用的语句并不是一个好主意。例如,编写类似 assert(x = 5) 的东西并不是一个好主意,因为 x 已更改,并且在禁用断言时不会发生此更改。 忽略断言 在 C/C++ 中,我们可以在编译时使用预处理器 NDEBUG 完全删除断言。
// The below program runs fine because NDEBUG is defined
# define NDEBUG
# include <assert.h>
int main()
{
int x = 7;
assert (x==5);
return 0;
}