typedef 是 C 語言中用於建立型別別名的關鍵字,能提升程式碼可讀性、簡化複雜型別宣告,並強化可移植性。本文詳細說明其語法、應用場景、與 #define 的差異,並提供實務範例。
語法:typedef 既有型別 新型別名稱;
typedef unsigned char BYTE;
此後 BYTE 即等同於 unsigned char,可直接宣告變數:
BYTE b1, b2;
慣例上別名使用全大寫,以區別於標準型別,但小寫亦合法:
typedef unsigned char byte;
搭配結構體使用時,可省略變數宣告時的 struct 關鍵字:
#include <stdio.h>
#include <string.h>
typedef struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
} Book; // 此處 Book 為新型別名稱
int main() {
Book book; // 直接使用 Book,無需 struct Books
strcpy(book.title, "C Programming");
strcpy(book.author, "Nuha Ali");
strcpy(book.subject, "C Programming Tutorial");
book.book_id = 6495407;
printf("Book title : %s\n", book.title);
printf("Book author : %s\n", book.author);
printf("Book subject : %s\n", book.subject);
printf("Book book_id : %d\n", book.book_id);
return 0;
}
輸出:
Book title : C Programming Book author : Nuha Ali Book subject : C Programming Tutorial Book book_id : 6495407
| 特性 | typedef | #define |
|---|---|---|
| 處理階段 | 編譯器處理 | 前置處理器處理 |
| 適用範圍 | 僅限型別別名 | 型別別名、數值常數、巨集等 |
| 語意檢查 | 編譯器進行型別檢查 | 單純文字取代,無語意檢查 |
| 指標宣告 | typedef int* IntPtr; IntPtr p1, p2; 兩者皆為指標 | #define IntPtr int* IntPtr p1, p2; 僅 p1 為指標 |
#include <stdio.h>
#define TRUE 1
#define FALSE 0
int main() {
printf("Value of TRUE : %d\n", TRUE);
printf("Value of FALSE : %d\n", FALSE);
return 0;
}
輸出:
Value of TRUE : 1 Value of FALSE : 0
typedef 能大幅簡化複雜函式指標宣告:
// 未使用 typedef
int (*compare)(const void*, const void*);
// 使用 typedef
typedef int (*CompareFunc)(const void*, const void*);
CompareFunc cmp = my_compare_func;
int32_t、uintptr_t),提升跨平台可移植性typedef 使用typedef 簡化typedef int Int; Int x; 中 Int 是型別,非變數typedef char* CharPtr; const CharPtr p; 實為 char* const p(常數指標),非 const char* ptypedef善用 typedef 能讓 C 程式碼更具表達力、更易維護,是進階 C 開發者的必備技能。