閱讀 Asterisk 源碼時發現一種優雅的結構體初始化寫法——指定初始化器。這是 C99 標準引入的特性,能顯著提升代碼可讀性與維護性。
ST t2;
t2.a = 4;
t2.b = 5;
t2.fun = test2;
ST t1 = {
.a = 1,
.b = 2,
.fun = test1
};
#include <stdio.h>
typedef void (*pFun)(int a);
typedef struct ST {
int a;
int b;
pFun fun;
} ST;
void test1(int a) { printf("test1 : %d\r\n", a); }
void test2(int a) { printf("test2 : %d\r\n", a); }
int main() {
// 指定初始化器寫法
ST t1 = {
.a = 1,
.b = 2,
.fun = test1
};
printf("%d\t%d\n", t1.a, t1.b);
t1.fun(3);
// 傳統寫法
ST t2;
t2.a = 4;
t2.b = 5;
t2.fun = test2;
printf("%d\t%d\n", t2.a, t2.b);
t2.fun(6);
return 0;
}
$ gcc test20120608.c -o test20120608 -std=c99
$ ./test20120608
1 2
test1 : 3
4 5
test2 : 6

| 特性 | 說明 |
|---|---|
| 字段順序無關 | 可按任意順序初始化,如 {.b=2, .a=1} |
| 部分初始化 | 未指定字段自動零初始化,避免垃圾值 |
| 可讀性強 | 字段名與值對應一目了然,減少誤賦值 |
| 嵌套結構友好 | 支援巢狀結構體的深層指定初始化 |
| 數組也適用 | 如 int arr[10] = {[5] = 100, [9] = 200}; |
// 嵌套結構體
typedef struct { int x, y; } Point;
typedef struct { Point center; int radius; } Circle;
Circle c = {
.center = { .x = 10, .y = 20 },
.radius = 5
};
// 數組指定初始化
int scores[5] = { [2] = 95, [4] = 100 }; // scores = {0, 0, 95, 0, 100}
-std=c99,MSVC 部分版本需 /std:c11 或更高)指定初始化器是現代 C 語言提升代碼質量的利器。在嵌入式、系統編程中大量使用結構體配置時,善用此特性能讓初始化邏輯清晰、抗重構能力強。推薦在所有新項目中採用。