Typedef 声明
来自 cppreference.cn
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 声明 |