typedef?typedef 不創建新型別,而是為現有型別建立同義詞。其核心價值在於:
SOCKET 比 int 更能表達意圖typedeftypedef int SIGNED_INT; // 基本型別別名
typedef unsigned char BYTE; // 常見嵌入式慣例
typedef unsigned short WORD;
typedef unsigned long DWORD;
SIGNED_INT a, b; // 等同 int a, b;
BYTE buffer[256]; // 等同 unsigned char buffer[256];
限制:long SIGNED_INT x; 非法,typedef 別名不可再加型別修飾詞。
typedefstruct 關鍵字)
struct Student {
char name[20];
int age;
};
struct Student s1; // 必須寫 struct
typedef 簡化寫法
typedef struct {
char name[20];
int age;
} Student; // 直接使用 Student
Student s1, s2; // 簡潔明瞭
typedef struct {
int x, y;
} Point;
typedef struct {
Point topLeft;
Point bottomRight;
} Rectangle;
FILE 型別
// stdio.h 內部定義(簡化版)
typedef struct {
short level;
unsigned flags;
char fd;
unsigned char hold;
short bsize;
unsigned char *buffer;
unsigned char *curp;
unsigned istemp;
short token;
} FILE;
// 使用者代碼
FILE *fp = fopen("data.txt", "r"); // 無需關心內部結構
標準庫將複雜結構封裝為不透明型別 FILE,使用者只操作指標,實現資訊隱藏與二進制相容。
typedef 最大價值場景
// 返回 int、接受兩個 int 參數的函數指標
int (*compare)(int, int);
typedef int (*CompareFunc)(int, int);
CompareFunc cmp = myCompare; // 變數宣告
void sort(int *arr, int n, CompareFunc cmp); // 參數宣告
CompareFunc getComparator(int mode); // 返回型別宣告
stdint.h 風格
// my_types.h - 專案統一型別定義
#if defined(_MSC_VER) && _MSC_VER < 1600 // VS2010 前無 stdint.h
typedef signed char int8_t;
typedef unsigned char uint8_t;
typedef signed short int16_t;
typedef unsigned short uint16_t;
typedef signed int int32_t;
typedef unsigned int uint32_t;
#else
#include
#endif
typedef int32_t Bool; // 專案統一布林
typedef uint32_t Handle; // 句柄型別
typedef int (*Callback)(void* context); // 回調型別
所有平台相關型別集中在一個頭檔,移植時只修改此檔。
| 誤區 | 正確理解 |
|---|---|
typedef 創建新型別 | 僅建立別名,型別相容性不變 |
typedef struct S { } S; 與 struct S { } 相同 | 前者 S 為型別名,後者 S 為標籤,名字空間不同 |
可對 typedef 型別再加修飾詞 | long MY_INT x; 非法(除非 MY_INT 是巨集) |
typedef 是 C 語言型別系統的「語法糖」,善用它能讓代碼自文檔化、平台解耦、宣告簡潔。建立專案級 types.h,統一定義 int32_t、Handle、Callback 等核心型別,是專業 C 專案的標準啟動動作。