Thetypedef declaration provides a way to declare an identifier as a type alias, to be used to replace a possibly complextype name
The keywordtypedef is used in adeclaration, in the grammatical position of astorage-class specifier, except that it does not affect storage or linkage:
typedefint int_t;// declares int_t to be an alias for the type inttypedefchar 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)
Contents |
If adeclaration usestypedef as storage-class specifier, every declarator in it defines an identifier as an alias to the type specified. Since only one storage-class specifier is permitted in a declaration, typedef declaration cannot bestatic or extern.
typedef declaration does not introduce a distinct type, it only establishes a synonym for an existing type, thus typedef names arecompatible with the types they alias. Typedef names share thename space with ordinary identifiers such as enumerators, variables and function.
A typedef for a VLA can only appear at block scope. The length of the array is evaluated each time the flow of control passes over the typedef declaration, as opposed to the declaration of the array itself: void copyt(int n){typedefint B[n];// B is a VLA, its size is n, evaluated now n+=1; B a;// size of a is n from before +=1int b[n];// a and b are different sizesfor(int i=1; i< n; i++) a[i-1]= b[i];} | (since C99) |
typedef name may be anincomplete type, which may be completed as usual:
typedefint 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 declarations are often used to inject names from the tagname space into the ordinary name space:
typedefstruct tnode tnode;// tnode in ordinary name space// is an alias to tnode in tag name spacestruct tnode{int count; tnode*left,*right;// same as struct tnode *left, *right;};// now tnode is also a complete typetnode s,*sp;// same as struct tnode s, *sp;
They can even avoid using the tag name space at all:
typedefstruct{double hi, lo;} range;range z,*zp;
Typedef names are also commonly used to simplify the syntax of complex declarations:
// array of 5 pointers to functions returning pointers to arrays of 3 intsint(*(*callbacks[5])(void))[3]; // same with typedefstypedefint arr_t[3];// arr_t is array of 3 inttypedef arr_t*(*fp)(void);// pointer to function returning arr_t*fp callbacks[5];
Libraries often expose system-dependent or configuration-dependent types as typedef names, to present a consistent interface to the users or to other library components:
#if defined(_LP64)typedefintwchar_t;#elsetypedeflongwchar_t;#endif
C++ documentation for typedef declaration |