struct 關鍵字定義新類型,成員可為任意類型。四種等價定義方式:
// (1) 分離標記與變量\
struct card { char *face; char *suit; };\
struct card aCard, deck[52], *cardPtr;\
\
// (2) 合併聲明\
struct card { char *face; char *suit; } aCard, deck[52], *cardPtr;\
\
// (3) 匿名結構,僅能在此處定義變量\
struct { char *face; char *suit; } aCard, deck[52], *cardPtr;\
\
// (4) typedef 別名,最推薦\
typedef struct { char *face; char *suit; } Card;\
Card aCard, deck[52], *cardPtr;
編譯器為滿足硬件訪問對齊要求(如 4 字節邊界),會在成員間插入填充字節。示例:
struct E { char c; int i; } e1, e2;
在 2 字節字長機器上,c 佔 1 字節,緊接 1 字節填充,i 從地址 2 開始。結構體不可直接用 == 比較,因填充字節值不確定。

struct card aCard = {"Three", "Hearts"};,少於成員數時剩餘自動置 0/NULL。aCard.suit (.)、`cardPtr->suit` (->),後者等價於 (*cardPtr).suit。const Card*)效率高且可防修改,推薦指針。代碼亮點:const char* 成員防止字面量被修改;函數參數精心設計 Card* const(指針常量)、const Card* const(指向常量的常量指針),體現最小權限原則。

union number { int x; double y; };
m._matrix.f[2][2] 整體操作與 m._matrix._f11 單元訪問。union { unsigned int i; char c; } test;\
test.i = 2;\
return test.c != 2; // 小端機器返回真
| 運算符 | 功能 | 示例 |
|---|---|---|
| & | 按位與 | 掩碼提取位 |
| | | 按位或 | 置位 |
| ^ | 按位異或 | 翻轉位、無臨時變量交換 |
| ~ | 按位取反 | 掩碼取反 |
| << | 左移 | 乘 2ⁿ、構建掩碼 |
| >> | 右移 | 除 2ⁿ、有符號數實現定義 |
void displayBits(unsigned value) {\
unsigned mask = 1u << 31;\
for (int c = 1; c <= 32; ++c) {\
putchar(value & mask ? '1' : '0');\
value <<= 1;\
if (c % 4 == 0) putchar(' ');\
}\
putchar('\\n');\
}

struct bitCard {\
unsigned face : 4; // 4位存花色 0-12\
unsigned suit : 2; // 2位存花色 0-3\
unsigned color: 1; // 1位存顏色 0/1\
};
unsigned : 19; 跳過 19 位,對齊下一存儲單元。unsigned : 0; 強制下一位域從新存儲單元開始。| 優點 | 缺點 |
|---|---|
| 極致節省內存 | 無法取地址(&)、無法構成數組 |
| 硬件寄存器映射天然契合 | 編譯器生成額外取值/設置指令,執行較慢 |
典型的空間換時間權衡。

enum months { JAN=1, FEB, MAR, APR, MAY, JUN,\
JUL, AUG, SEP, OCT, NOV, DEC };\
// JAN=1,後續遞增,DEC=12
int,可隱式轉換,但建議顯式轉型 (enum months)(val)。
typedef、指針傳參、const 修飾,注意對齊填充。#define 常量,提供類型安全與調試符號信息。這五大特性構成了 C 語言處理複雜數據結構、底層硬件交互、高性能存儲的核心工具箱,深度掌握是成為資深 C 開發者的必經之路。