52 lines
1.4 KiB
Markdown
52 lines
1.4 KiB
Markdown
# 观察
|
||
|
||
首先来看一段代码,这段代码可能和你平常写的也差不多,但是也有一些区别
|
||
|
||
[在线运行](https://godbolt.org/z/56h6qMhTh)
|
||
```c
|
||
#include <assert.h>
|
||
|
||
int main(void) {
|
||
int a = 3;
|
||
int b = 5;
|
||
|
||
assert(a + b == 8);
|
||
}
|
||
```
|
||
|
||
|
||
编译运行它,结果是什么都没有,这说明没有问题,那么如果不小心打错了呢,比如你是复制粘贴的第四行只改了变量名
|
||
|
||
|
||
[在线运行](https://godbolt.org/z/ehfed3zv3)
|
||
``` C
|
||
#include <assert.h>
|
||
|
||
int main(void) {
|
||
int a = 3;
|
||
int b = 3;
|
||
|
||
assert(a + b == 8);
|
||
}
|
||
```
|
||
|
||
|
||
那么很快,当你运行时,程序就会提示你预先认为的`a + b == 8`并不成立,导致出错的代码是`/app/example.c`他的行数是`7`。
|
||
|
||
```
|
||
我们把 /app/example.c:7 叫位置信息
|
||
其中/app/example.c是文件名
|
||
7是行数
|
||
有了这两个就可以精确定位出问题的代码附近
|
||
```
|
||
|
||
`assert`是一个宏,来自于`<assert.h>`, 的确是标准C语言但是大家可能平时见得很少,它的作用你可能已经知道了就是
|
||
|
||
```
|
||
assert( 表达式 ) : 在表达式不成立(0值)的情况,报一个错,清晰指出是哪个表达式,在哪个程序第几行
|
||
```
|
||
|
||
这么一个简单的操作,它的威力并不简单,要不然我也不会特意为此写一个以此为中心的教程来介绍有关的用途,以及现实世界很多与它类似的实践。
|
||
|
||
|