接上篇,詳細講解 goto、void、return、const、volatile、extern、struct、union、enum、typedef 十大關鍵字。
「代碼質量與 goto 使用次數成反比」—— 建議禁用,改用結構化控制流。
| 場景 | 用法 | 示例 |
|---|---|---|
| 無返回值函數 | 修飾返回類型 | void func(); |
| 無參數函數 | 參數列表 | int func(void); |
| 通用指針 | void* 接收任意指針 | void* ptr = &x; |
| 指針運算限制 | 不可直接算術 | void* p; p++ // 錯誤 |
注意:void 不能定義實際變量。
return (expr); 括號可省略return 僅一條執行const int i = 2; 等價 int const i = 2;const int *p; // p可變,*p不可變(指向常量的指針) int const *p; // 同上 int *const p; // p不可變,*p可變(常量指針) const int *const p; // p與*p均不可變
void func(const int x); 防止誤修改const int func(); 返回值不可修改extern const int i;(不可賦值)告訴編譯器:該變量可能被未知因素(硬件、中斷、其他線程)修改,禁止優化,每次必須從內存讀取。
volatile int flag; // 硬件寄存器、共享標誌位 volatile int *ptr; // 指向易變內存的指針
聲明而非定義,告訴編譯器符號在別處定義:
// a.c int global = 10; // b.c extern int global; // 使用 a.c 定義的 global
int arr[];,配合 malloc 實現變長結構| 特性 | enum | #define |
|---|---|---|
| 處理階段 | 編譯期 | 預編譯期 |
| 調試可見性 | 可見 | 不可見 |
| 批量定義 | 一次定義多個 | 每次一個 |
| 類型安全 | 有 | 無 |
關鍵區別:typedef 創建新類型名,參與類型系統;#define 純文本替換。
#define INT32 int typedef int int32; unsigned INT32 x = 10; // 合法:展開為 unsigned int unsigned int32 y = 10; // 錯誤:int32 不能與 unsigned 組合
最佳實踐:優先使用 typedef,配合 stdint.h 固定寬度類型(int32_t 等)。