C 語言早期無原生布爾類型,開發者常用 `int` 或 `char` 模擬。C99 標準引入 `_Bool` 關鍵字與 `
| 階段 | 做法 | 缺陷 |
|---|---|---|
| K&R C / C89 | `typedef int bool; #define TRUE 1 #define FALSE 0` | 佔 4 字節,浪費內存 |
| 內存敏感場景 | `typedef char bool; #define TRUE 1 #define FALSE 0` | 1 字節,但非標準,可移植性差 |
| C99 (1999) | `#include | 標準化,`sizeof(_Bool)==1`,與 C++ `bool` 兼容 |
#ifndef _STDBOOL_H
#define _STDBOOL_H
#ifndef __cplusplus
#define bool _Bool
#define true 1
#define false 0
#else
#define _Bool bool
#define bool bool
#define false false
#define true true
#endif
#define __bool_true_false_are_defined 1
#endif
bool bb = 10;
bool aa = 0;
printf("%d %d\n", bb, aa); // 輸出:1 0
賦值非 0 時自動歸一化為 1,語義純粹。
升級到 C99+,拥抱標準 `bool`,讓代碼更現代、更安全!