基本調用語法
// 1. 無參數 void 函數
void greet(void) { puts("Hello!"); }
greet(); // 直接調用,括號不可省略
// 2. 有參數 void 函數
void print_int(int x) { printf("%d\n", x); }
print_int(42); // 傳遞實參
// 3. 返回 void 的函數指針
void (*func_ptr)(int) = print_int;
func_ptr(100); // 透過指針調用
常見誤區
| 錯誤代碼 | 問題 | 正確寫法 |
void f(); f; | 缺少 (),僅為函數指標表達式,不調用 | f(); |
void f(int); f(1, 2); | 實參數量不匹配 | f(1); |
void f(void); int x = f(); | 嘗試接收無返回值 | 直接 f(); |
void 參數列表 vs 空參數列表
// C 標準區別
void f1(); // 老式寫法:參數未指定,調用時可傳任意參數 (危險)
void f2(void); // 現代寫法:明確無參數,調用傳參編譯報錯
// 建議:所有無參函數均寫 void
void init(void) { ... }
實戰模式:回調函數
// 通用排序框架:比較邏輯外部傳入
void sort(void *base, size_t n, size_t sz,
int (*cmp)(const void *, const void *)) {
// ... 冒泡/快排核心,調用 cmp 比較 ...
}
// 使用
int cmp_int(const void *a, const void *b) {
return *(const int*)a - *(const int*)b;
}
int arr[] = {5,2,8,1};
sort(arr, 4, sizeof(int), cmp_int);
總結
void 表示 **無返回值**,調用時 **只寫函數名 + () + 實參**。
- **宣告/定義** 參數列表 **務必寫
void** (或具體類型),杜絕老式 ()。
- **函數指針** 型別必須完全匹配 (返回值、參數列表),回調是 C 語言多態核心。