Typedef 宣告
來自 cppreference.com
typedef 宣告 提供了一種將識別符號宣告為類型別名的方法,用於替代可能複雜的型別名。
關鍵字 typedef 在宣告中使用,其語法位置與儲存類說明符相同,但它不影響儲存或連結。
typedef int int_t; // declares int_t to be an alias for the type int typedef char char_t, *char_p, (*fp)(void); // declares char_t to be an alias for char // char_p to be an alias for char* // fp to be an alias for char(*)(void)
目錄 |
[編輯] 解釋
如果一個宣告使用 typedef 作為儲存類說明符,則其中每個宣告符都將一個識別符號定義為指定型別的別名。由於一個宣告中只允許一個儲存類說明符,因此 typedef 宣告不能是 static 或 extern。
typedef 宣告不引入不同的型別,它只是為現有型別建立一個同義詞,因此 typedef 名稱與它們所別名的型別是相容的。typedef 名稱與普通識別符號(如列舉器、變數和函式)共享名稱空間。
VLA 的 typedef 只能出現在塊作用域內。陣列的長度在每次控制流透過 typedef 宣告時進行評估,而不是在陣列本身的宣告時進行評估。 void copyt(int n) { typedef int B[n]; // B is a VLA, its size is n, evaluated now n += 1; B a; // size of a is n from before +=1 int b[n]; // a and b are different sizes for (int i = 1; i < n; i++) a[i-1] = b[i]; } |
(C99 起) |
[編輯] 注意
typedef 名稱可能是一個不完整型別,可以像往常一樣完成。
typedef int A[]; // A is int[] A a = {1, 2}, b = {3,4,5}; // type of a is int[2], type of b is int[3]
typedef 宣告通常用於將來自標籤名稱空間的名稱注入到普通名稱空間中。
typedef struct tnode tnode; // tnode in ordinary name space // is an alias to tnode in tag name space struct tnode { int count; tnode *left, *right; // same as struct tnode *left, *right; }; // now tnode is also a complete type tnode s, *sp; // same as struct tnode s, *sp;
它們甚至可以完全避免使用標籤名稱空間。
typedef struct { double hi, lo; } range; range z, *zp;
Typedef 名稱也常用於簡化複雜宣告的語法。
// array of 5 pointers to functions returning pointers to arrays of 3 ints int (*(*callbacks[5])(void))[3]; // same with typedefs typedef int arr_t[3]; // arr_t is array of 3 int typedef arr_t* (*fp)(void); // pointer to function returning arr_t* fp callbacks[5];
庫通常將依賴於系統或配置的型別作為 typedef 名稱公開,以向用戶或其他庫元件提供一致的介面。
#if defined(_LP64) typedef int wchar_t; #else typedef long wchar_t; #endif
[編輯] 參考
- C23 標準 (ISO/IEC 9899:2024)
- 6.7.8 型別定義 (p: TBD)
- C17 標準 (ISO/IEC 9899:2018)
- 6.7.8 型別定義 (p: TBD)
- C11 標準 (ISO/IEC 9899:2011)
- 6.7.8 型別定義 (p: 137-138)
- C99 標準 (ISO/IEC 9899:1999)
- 6.7.7 型別定義 (p: 123-124)
- C89/C90 標準 (ISO/IEC 9899:1990)
- 3.5.6 型別定義
[編輯] 關鍵字
[編輯] 另請參閱
C++ 文件,關於
typedef 宣告 |