@@ -284,6 +284,50 @@ uint8_t z{1000}; // C++ 编译错误!1000 超出 uint8_t 范围
284284
285285提示:可以用一个宏来减少重复代码。
286286
287+ ###练习 1 参考答案
288+
289+ ``` c
290+ #include < stdio.h>
291+ #include < stdint.h>
292+ // #include <stddef.h>
293+
294+ int main () {
295+ // 基本类型
296+ printf ("sizeof(char) = %zu bytes\n", sizeof(char));
297+ printf("sizeof(short) = %zu bytes\n", sizeof(short));
298+ printf("sizeof(int) = %zu bytes\n", sizeof(int));
299+ printf("sizeof(long) = %zu bytes\n", sizeof(long));
300+ printf("sizeof(long long) = %zu bytes\n", sizeof(long long));
301+
302+ // 定长整数类型 (需包含 <stdint.h>)
303+ printf ("sizeof(int8_t) = %zu bytes\n", sizeof(int8_t));
304+ printf("sizeof(uint8_t) = %zu bytes\n", sizeof(uint8_t));
305+ printf("sizeof(int32_t) = %zu bytes\n", sizeof(int32_t));
306+ printf("sizeof(uint32_t) = %zu bytes\n", sizeof(uint32_t));
307+ printf("sizeof(int64_t) = %zu bytes\n", sizeof(int64_t));
308+
309+ // size_t 类型 (需包含<stdio.h>、 <stddef.h> 或 <stdlib.h>)
310+ printf ("sizeof(size_t) = %zu bytes\n", sizeof(size_t));
311+
312+ return 0;
313+ }
314+
315+ ```
316+
317+ ``` 终端输出
318+ sizeof(char) = 1 bytes
319+ sizeof(short) = 2 bytes
320+ sizeof(int) = 4 bytes
321+ sizeof(long) = 4 bytes
322+ sizeof(long long) = 8 bytes
323+ sizeof(int8_t) = 1 bytes
324+ sizeof(uint8_t) = 1 bytes
325+ sizeof(int32_t) = 4 bytes
326+ sizeof(uint32_t) = 4 bytes
327+ sizeof(int64_t) = 8 bytes
328+ sizeof(size_t) = 8 bytes
329+ ```
330+
287331### 练习 2:溢出观察
288332
289333分别对有符号 ` int ` 和无符号 ` unsigned int ` 做溢出实验:
@@ -306,6 +350,28 @@ int main(void)
306350
307351编译运行,观察两者的行为差异。然后加上 `-fsanitize=undefined` 选项重新编译,看看有什么变化。
308352
353+ ### 练习 2 参考答案
354+
355+ 假设该文件名为overflow.c
356+
357+ 使用 gcc overflow.c -o overflow && ./overflow 编译运行后,你大概率会看到如下输出:
358+
359+ ```终端输出
360+ INT_MAX = 2147483647, INT_MAX + 1 = -2147483648
361+ UINT_MAX = 4294967295, UINT_MAX + 1 = 0
362+ ```
363+
364+ 使用 gcc -fsanitize=undefined overflow.c -o overflow_ubsan && ./overflow_ubsan 编译运行后,你会看到类似如下的输出:
365+
366+ ``` 终端输出
367+ INT_MAX = 2147483647, INT_MAX + 1 = -2147483648
368+ overflow.c:9:54: runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'
369+ UINT_MAX = 4294967295, UINT_MAX + 1 = 0
370+ ```
371+ 为什么?
372+ 实际上 C 标准其实并没有对带有符号的整数的溢出进行定义,也就是说,对INT_MAX进行+1这个操作严格意义上是一个未定义行为。
373+ (只不过溢出很好用,也是大部分编译器都默认支持译出的。)
374+
309375## 参考资源
310376
311377- [ cppreference: C 语言整型] ( https://en.cppreference.com/w/c/language/integer_constant )
0 commit comments