File tree 3 files changed +78
-86
lines changed
3 files changed +78
-86
lines changed Original file line number Diff line number Diff line change 10
10
11
11
## 1.第一个断言案例
12
12
13
- 断言,** 是宏,而非函数** 。assert 宏的原型定义在 <assert.h>(C)、<cassert >(C++)中,其作用是如果它的条件返回错误,则终止程序执行。可以通过定义 NDEBUG 来关闭 assert,但是需要在源代码的开头,include <assert.h> 之前。
13
+ 断言,** 是宏,而非函数** 。
14
+
15
+ assert 宏的原型定义在 <assert.h>(C)、<cassert >(C++)中。其作用是如果它的条件返回错误,则终止程序执行。
16
+
17
+ 可以通过定义 ` NDEBUG ` 来关闭 assert,** 但是需要在源代码的开头,include <assert.h> 之前。**
14
18
15
19
``` c
16
20
void assert (int expression);
17
21
```
18
- 对应代码:[assert.c](./assert.c)
22
+
23
+ > 代码样例:[assert.c](./assert.c)
19
24
```c
20
25
#include <stdio.h>
21
26
#include <assert.h>
@@ -35,22 +40,22 @@ int main()
35
40
36
41
return 0;
37
42
}
38
-
39
43
```
40
44
输出:
41
45
``` c
42
- assert: assert.c:13 : main: Assertion ` x==7' failed.
46
+ assert: assert.c:13 : main: Assertion ' x==7' failed.
43
47
```
44
48
可以看到输出会把源码文件,行号错误位置,提示出来!
45
49
46
50
## 2.断言与正常错误处理
47
51
48
- 断言主要用于检查逻辑上不可能的情况。例如,它们可用于检查代码在开始运行之前所期望的状态,或者在运行完成后检查状态。与正常的错误处理不同,断言通常在运行时被禁用 。
52
+ + 断言主要用于检查逻辑上不可能的情况。
49
53
50
- 忽略断言:
54
+ > 例如,它们可用于检查代码在开始运行之前所期望的状态,或者在运行完成后检查状态。与正常的错误处理不同,断言通常在运行时被禁用。
51
55
52
- 在代码开头加上:
56
+ + 忽略断言, 在代码开头加上:
53
57
``` c++
54
58
#define NDEBUG // 加上这行,则 assert 不可用
55
59
```
56
- 对应学习的代码:[ ignore_assert.c] ( ./ignore_assert.c )
60
+
61
+ > 样例代码:[ ignore_assert.c] ( ./ignore_assert.c )
Original file line number Diff line number Diff line change 6
6
* @date 2019-07-25
7
7
*/
8
8
9
- # define NDEBUG
9
+ # define NDEBUG // 忽略断言
10
10
11
11
#include <assert.h>
12
12
13
-
14
-
15
13
int main (){
16
14
int x = 7 ;
17
15
assert (x == 5 );
You can’t perform that action at this time.
0 commit comments