*** Welcome to piglix ***

Typedef


typedef is a reserved keyword in the C and C++ programming languages. It is used to create an alias name for another data type. As such, it is often used to simplify the syntax of declaring complex data structures consisting of struct and union types, but is just as common in providing specific descriptive type names for integer data types of varying lengths. The C standard library and POSIX reserve the suffix '_t', for example as in size_t and time_t.

The syntax for a creating a typedef is: typedef typedeclaration;

Some examples:

creates Length as a synonym for int.

creates PFI as a synonym for a pointer to a function of two char * arguments that returns an int.

A typedef declaration may be used to indicate the meaning of a variable within the programming context, e.g., it may be include the expression of a unit of measurement or counts. The generic declarations in the following code,

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 represented by the same data type int, represent 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:

Although the compiler considers km_per_hour to be equivalent to int in the above code, the two cannot be used interchangeably when the type is changed via a prefix of unsigned, signed, or long.

A typedef may be used to simplify the declaration of a compound type (struct, union) or pointer type. For example, in the following snippet:

the data type struct MyStruct is defined. To declare a variable of this type in C, the struct key word is required (in C++, it may be omitted):


...
Wikipedia

...