Skip to content

Commit ff24fb6

Browse files
committed
小修改
1 parent 9852955 commit ff24fb6

File tree

3 files changed

+33
-0
lines changed

3 files changed

+33
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# 初识断言 (Assertion)
2+
3+
## 1. 什么是断言
4+
5+
断言是用于进行 **调试****错误处理** 的工具。
6+
7+
它允许程序员在代码中插入条件检查,以确保程序在运行时满足特定的前提条件。
8+
9+
如果断言的条件不成立,程序将中止执行并生成一条错误消息,提供关于出错位置和原因的信息。
10+
11+
## 2. 使用断言
12+
13+
```c
14+
#include <assert.h>
15+
16+
int main(void){
17+
int a = -5;
18+
assert(a > 0);
19+
}
20+
```
21+
22+
程序中止执行,因为断言的条件 `a > 0` 不成立。
23+
24+
## 3. 用途
25+
26+
用于 **防御性编程**,缩小错误可能存在的范围,便于调试。

教程/示例代码/语法和标准库/18_泛型选择/vector.c

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
#include <stdbool.h>
12
#include <stdint.h>
23
#include <stdlib.h>
34

教程/示例代码/语法和标准库/8_BMI测试.c

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
#include <assert.h>
12
#include <stdio.h>
23

34
int main()
@@ -7,9 +8,14 @@ int main()
78
// 获取用户输入
89
printf("请输入您的体重(单位:千克):");
910
scanf("%f", &weight);
11+
12+
assert(weight != 0);
13+
1014
printf("请输入您的身高(单位:厘米):");
1115
scanf("%f", &height);
1216

17+
assert(height != 0);
18+
1319
// 换算
1420
height /= 100;
1521

0 commit comments

Comments
 (0)