assert()
[英文原文地址assert()
](https://www.sharetechnote.com/html/C_assert.html)
`assert()`函数的功能非常简单。可以简单地描述如下:
```c
void assert(int expression);
```
这个表达式可以是任何返回整数值的C表达式(通常是比较语句)。如果表达式给出非负值(即值大于等于0),则`assert`什么都不做;但如果表达式给出负值,它会在标准错误输出(即控制台)上打印错误消息,并中止(终止)程序。这里的关键词是'abort(terminate) the program'。
它通常用于调试目的,以及在程序继续执行之前确保满足某个条件时使用。
虽然`assert()`是一个方便的函数,但建议你对其工作原理和为什么使用它有一个清晰的理解。以下几点可能有助于你:
- 你可以通过定义`NDEBUG`来禁用`assert()`。这既方便又烦人,具体取决于你的使用方式。它可以方便地工作,因为如果你不想使用`assert()`,只需定义`NDEBUG`即可,这样它就不会被散布在你的代码中,也不会带来任何性能开销。但如果误用它,可能会让人烦恼。例如,如果你执行`assert(x++)`,然后定义了`NDEBUG`,那么`x++`将不会被求值,因为`assert(x++)`根本不会被编译。除非你知道会发生什么,否则不要在`assert()`中放入除比较表达式以外的任何表达式。
```c
Example 01 >
#include <assert.h> // you need to include assert.h to use assert() function.
#include <stdio.h>
int main()
{
int x;
x = -1;
assert(x >= 0); // the expression within assert() gives FALSE, so assert() will be triggered
printf("Hello World ! \n");
return 1;
}```
Example 02 >
#include <assert.h>
#include <stdio.h>
int main()
{
int x;
x = -1;
assert(x >= 0 && "x cannot be a negative value"); // you can put your own message in this way.
printf("Hello World ! \n");
return 1;
}
Example 03 >
#define NDEBUG // you can disable assert() by defining NDEBUG.
// You have the define this before #include <assert.h>
#include <assert.h>
#include <stdio.h>
int main()
{
int x;
x = -1;
assert(x >= 0 && "x cannot be a negative value");
printf("Hello World ! \n");
return 1;
}