吾爱程序员:这里有好玩的游戏和软件
当前位置:首页C语言教程 → C语言中的断言

C语言中的断言

来源:网络 | 更新时间:2022-02-05 07:54:02
断言是用于测试程序员所做假设的语句。例如,我们可以使用断言来检查 malloc() 返回的指针是否为 NULL。  以下是断言的语法。
void assert( int expression ); 
如果表达式的计算结果为 0 (false),则表达式、源代码文件名和行号被发送到标准错误,然后调用 abort() 函数。  例如,考虑以下程序。 
#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;
}
上面的程序编译并运行良好。  在 Java 中,默认情况下不启用断言,我们必须将选项传递给运行时引擎以启用它们。

最新文章

热点资讯

手游排行榜

CopyRight 2020-2030吾爱程序员

鄂ICP备2021004581号-8

本站资源收集于网络,如有侵权请联系我们:35492删除0109@qq.com