📜  C / C++中的断言

📅  最后修改于: 2021-05-30 20:00:31             🧑  作者: Mango

断言是用于测试程序员所作假设的语句。例如,我们可以使用断言来检查malloc()返回的指针是否为NULL。

以下是断言的语法。

void assert( int expression ); 

如果expression的计算结果为0(假),则将表达式,源代码文件名和行号发送到标准错误,然后调用abort()函数。

例如,考虑以下程序。

#include 
#include 
  
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++中,我们可以使用预处理程序NODEBUG在编译时完全删除断言。

// The below program runs fine because NDEBUG is defined
# define NDEBUG
# include 
  
int main()
{
    int x = 7;
    assert (x==5);
    return 0;
}

上面的程序可以编译并正常运行。

在Java,默认情况下不启用断言,我们必须将选项传递给运行时引擎以启用它们。

参考:
http://en.wikipedia.org/wiki/Assertion_%28software_development%29

要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”