Typedef
Typedef
Main page

Typedef

logo
Community Hub0 subscribers
What are your thoughts?
Be the first to start a discussion here.
Be the first to start a discussion here.
Typedef

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 _t, such as in size_t and time_t. This is practiced in some other coding systems, although POSIX explicitly reserves this practice for POSIX data types. In modern codebases, especially in C++, this _t suffix is no longer popular, but does appear in some types in the C++ Standard Library along with other suffixes like _v.

This creates the type Length as a synonym of the type int:

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,

may be expressed by declaring context specific types:

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 int, store different or incompatible data. The definition in congratulate() of your_score indicates to the programmer that current_speed (or any other variable not declared as a Points) should not be passed as an argument. This would not be as apparent if both were declared as variables of int datatype. However, the indication is for the programmer only; the C/C++ compiler considers both variables to be of type int and does not flag type mismatch warnings or errors for "wrong" argument types for congratulate(Points your_score) in the code snippet below:

A typedef may be used to simplify the declarations of objects having types with verbose names, such as struct, union, or pointer types. For example,

See all
User Avatar
No comments yet.