File tree Expand file tree Collapse file tree
documents/vol1-fundamentals/c_tutorials Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -284,7 +284,7 @@ uint8_t z{1000}; // C++ 编译错误!1000 超出 uint8_t 范围
284284
285285提示:可以用一个宏来减少重复代码。
286286
287- ###练习 1 参考答案
287+ ### 练习 1 参考答案
288288
289289``` c
290290#include < stdio.h>
@@ -314,7 +314,7 @@ int main() {
314314
315315```
316316
317- ``` 终端输出
317+ ``` text
318318sizeof(char) = 1 bytes
319319sizeof(short) = 2 bytes
320320sizeof(int) = 4 bytes
@@ -328,6 +328,8 @@ sizeof(int64_t) = 8 bytes
328328sizeof(size_t) = 8 bytes
329329```
330330
331+ 注意 ` sizeof(long) ` 这里是 4,但 ` sizeof(size_t) ` 已经是 8 了,说明这份输出来自 LLP64 环境(比如 64 位 Windows):这种模型下指针 8 字节,` long ` 却只有 4。换到 64 位的 Linux 或 macOS(LP64),` long ` 就是 8 字节。你在自己机器上看到 ` sizeof(long) = 8 ` ,程序没写错,是数据模型的差别。
332+
331333### 练习 2:溢出观察
332334
333335分别对有符号 ` int ` 和无符号 ` unsigned int ` 做溢出实验:
@@ -356,21 +358,22 @@ int main(void)
356358
357359使用 gcc overflow.c -o overflow && ./overflow 编译运行后,你大概率会看到如下输出:
358360
359- ```终端输出
361+ ```text
360362INT_MAX = 2147483647, INT_MAX + 1 = -2147483648
361363UINT_MAX = 4294967295, UINT_MAX + 1 = 0
362364```
363365
364366使用 gcc -fsanitize=undefined overflow.c -o overflow_ubsan && ./overflow_ubsan 编译运行后,你会看到类似如下的输出:
365367
366- ``` 终端输出
368+ ``` text
367369INT_MAX = 2147483647, INT_MAX + 1 = -2147483648
368370overflow.c:9:54: runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'
369371UINT_MAX = 4294967295, UINT_MAX + 1 = 0
370372```
373+
371374为什么?
372375实际上 C 标准其实并没有对带有符号的整数的溢出进行定义,也就是说,对INT_MAX进行+1这个操作严格意义上是一个未定义行为。
373- (只不过溢出很好用,也是大部分编译器都默认支持译出的 。)
376+ (只不过溢出很好用,也是大部分编译器都默认支持溢出的 。)
374377
375378## 参考资源
376379
Original file line number Diff line number Diff line change @@ -325,7 +325,7 @@ int main(void)
325325 float e_float = 0.3f;
326326 float f_float = 0.4f;
327327 float g_float = 0.7f;
328-
328+
329329 printf("a_double + b_double == c_double? %s\n", (a_double + b_double == c_double) ? "yes" : "no");
330330 printf("a_float + b_float == c_float? %s\n", (a_float + b_float == c_float) ? "yes" : "no");
331331 printf("e_float + f_float == g_float? %s\n", (e_float + f_float == g_float) ? "yes" : "no");
@@ -339,7 +339,7 @@ int main(void)
339339}
340340```
341341
342- ```终端输出
342+ ```text
343343a_double + b_double == c_double? no
344344a_float + b_float == c_float? yes
345345e_float + f_float == g_float? no
@@ -381,6 +381,7 @@ if (target < (int)sizeof(values) / (int)sizeof(values[0])) {
381381 printf("target is in range\n");
382382}
383383```
384+
384385或者
385386
386387``` c
You can’t perform that action at this time.
0 commit comments