typedef is a reserved keyword in the programming languages C, C++, and Objective-C. It is used to create an additional name (alias) for another data type, but does not create a new type, except in the obscure case of a qualified typedef of an array type where the typedef qualifiers are transferred to the array element type. As such, it is often used to simplify the syntax of declaring complex data structures consisting of struct and union types, although it is also commonly used to provide specific descriptive type names for integer data types of varying sizes.
A typedef declaration follows the same syntax as declaring any other C identifier. The keyword typedef itself is a specifier which means that while it typically appears at the start of the declaration, it can also appear after the type specifiers or between two of them.
In the C standard library and in POSIX specifications, the identifier for the typedef definition is often suffixed with , such as in size_t and time_t. This is practiced in other coding systems, although POSIX explicitly reserves this practice for POSIX data types.
This creates the type as a synonym of the type :
typedef int length;
A typedef declaration may be used as documentation by indicating the meaning of a variable within the programming context, e.g., it may include the expression of a unit of measurement or counts. The generic declarations,
int current_speed;
int high_score;
void congratulate(int your_score) {
if (your_score > high_score) {
// ...
}
}
may be expressed by declaring context specific types:
typedef int km_per_hour;
typedef int points;
// km_per_hour
is synonymous with int
here, and thus, the compiler treats
// our new variables as integers.
km_per_hour current_speed;
points high_score;
void congratulate(points your_score) {
if (your_score > high_score) {
// ...
}
}
Both sections of code execute identically. However, the use of typedef declarations in the second code block makes it clear that the two variables, while representing the same data type , store different or incompatible data.