assert那些事¶
1.第一个断言案例¶
断言,是宏,而非函数。assert 宏的原型定义在
#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;
}
2.断言与正常错误处理¶
断言主要用于检查逻辑上不可能的情况。例如,它们可用于检查代码在开始运行之前所期望的状态,或者在运行完成后检查状态。与正常的错误处理不同,断言通常在运行时被禁用。
忽略断言:
在代码开头加上:
对应学习的代码:ignore_assert.c