C库中的宏assert允许将诊断信息写入标准错误文件。也就是它可以用于在C程序中添加诊断程序。
声明:
void assert(int expression);
expression——可以是变量或任意C表达式。如果expression的计算结果为TRUE,则assert()不执行任何操作。如果expression的计算结果为FALSE,则assert()在标准错误流(用于显示错误消息和诊断的标准错误流)上显示错误消息,并中止程序执行。
举个例子:see: assert geeksforgeeks
#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.
参考资料:
- https://www.geeksforgeeks.org/assertions-cc/
- https://www.tutorialspoint.com/c_standard_library/c_macro_assert.htm