refine content of assert and const
This commit is contained in:
@@ -10,12 +10,17 @@
|
||||
|
||||
## 1.第一个断言案例
|
||||
|
||||
断言,**是宏,而非函数**。assert 宏的原型定义在 <assert.h>(C)、<cassert>(C++)中,其作用是如果它的条件返回错误,则终止程序执行。可以通过定义 NDEBUG 来关闭 assert,但是需要在源代码的开头,include <assert.h> 之前。
|
||||
断言,**是宏,而非函数**。
|
||||
|
||||
assert 宏的原型定义在 <assert.h>(C)、<cassert>(C++)中。其作用是如果它的条件返回错误,则终止程序执行。
|
||||
|
||||
可以通过定义 `NDEBUG` 来关闭 assert,**但是需要在源代码的开头,include <assert.h> 之前。**
|
||||
|
||||
```c
|
||||
void assert(int expression);
|
||||
```
|
||||
对应代码:[assert.c](./assert.c)
|
||||
|
||||
> 代码样例:[assert.c](./assert.c)
|
||||
```c
|
||||
#include <stdio.h>
|
||||
#include <assert.h>
|
||||
@@ -35,22 +40,22 @@ int main()
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
```
|
||||
输出:
|
||||
```c
|
||||
assert: assert.c:13: main: Assertion `x==7' failed.
|
||||
assert: assert.c:13: main: Assertion 'x==7' failed.
|
||||
```
|
||||
可以看到输出会把源码文件,行号错误位置,提示出来!
|
||||
|
||||
## 2.断言与正常错误处理
|
||||
|
||||
断言主要用于检查逻辑上不可能的情况。例如,它们可用于检查代码在开始运行之前所期望的状态,或者在运行完成后检查状态。与正常的错误处理不同,断言通常在运行时被禁用。
|
||||
+ 断言主要用于检查逻辑上不可能的情况。
|
||||
|
||||
忽略断言:
|
||||
>例如,它们可用于检查代码在开始运行之前所期望的状态,或者在运行完成后检查状态。与正常的错误处理不同,断言通常在运行时被禁用。
|
||||
|
||||
在代码开头加上:
|
||||
+ 忽略断言,在代码开头加上:
|
||||
```c++
|
||||
#define NDEBUG // 加上这行,则 assert 不可用
|
||||
```
|
||||
对应学习的代码:[ignore_assert.c](./ignore_assert.c)
|
||||
|
||||
> 样例代码:[ignore_assert.c](./ignore_assert.c)
|
||||
|
@@ -6,12 +6,10 @@
|
||||
* @date 2019-07-25
|
||||
*/
|
||||
|
||||
# define NDEBUG
|
||||
# define NDEBUG // 忽略断言
|
||||
|
||||
#include<assert.h>
|
||||
|
||||
|
||||
|
||||
int main(){
|
||||
int x=7;
|
||||
assert(x==5);
|
||||
|
Reference in New Issue
Block a user