命名空间
变体
动作

Typedef 声明

来自 cppreference.cn
< c‎ | language

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: 待定)
  • C17 标准 (ISO/IEC 9899:2018)
  • 6.7.8 类型定义 (p: 待定)
  • 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 类型定义

[编辑] 关键字

typedef

[编辑] 参见

C++ 文档 关于 typedef 声明