enum Color { RED, YELLOW, GREEN, NUM_COLORS };
int,預設從 0 遞增。enum { RED=1, YELLOW, GREEN=5 },後續繼續遞增。NUM_COLORS 取得元素總數,便於陣列邊界檢查。enum Color { RED, YELLOW, GREEN, NUM_COLORS };
char *names[NUM_COLORS] = { "red", "yellow", "green" };
int choice; scanf("%d", &choice);
if (choice >= 0 && choice < NUM_COLORS) printf("You chose %s\n", names[choice]);
// 具名結構標籤,後續可複用
struct Point { int x, y; };
struct Point p1, p2;
// 匿名結構直接定義變數,無法複用型別
struct { int x, y; } p3, p4;
p1.x = 10; p1.y = 20;p1 = p2;(逐成員複製)p1 = (struct Point){5, 10};struct Date d = {.month=4, .year=2025};-> 運算符struct Date today = {4, 26, 2025};
struct Date *p = &today;
p->month = 5; // 等價於 (*p).month = 5;
注意:結構變數名不是地址,必須用 & 取址。
const 防誤改。// 傳值範例:計算明天日期
struct Date tomorrow(struct Date d) { ... }
// 傳址範例:修改原物件
void advance_day(struct Date *d) { ... }
struct Date dates[100] = { {4,5,2025}, {12,25,2025} }; // 結構陣列
struct DateTime { struct Date d; struct Time t; }; // 巢狀結構(成員為結構)
struct Rect { struct Point pt1, pt2; }; // 嵌套結構
struct Rect r; r.pt1.x = 1; // 多層成員存取
文中包含完整可編譯範例:
所有範例均附帶輸出結果,便於驗證理解。