typedef existing data type alias; |
typedef unsigned long ulong; | ulong file_length; |
(a) | (b) | (c) |
typedef
keyword creates a new, usually shorter, name or alias for an existing data type.
typedef
statement is straightforward. The "alias" consists of exactly one word. Therefore, all text between the keyword and the alias, regardless of the number of words or lines, forms the "existing data type."unsigned long
. Programmers can create a new shorthand name or alias with a typedef
statement or with a macro: #define unsigned long ulong
. The compiler component processes typedef
statements, which are fully type-checked and the preferred method. The preprocessor implements macros by replacing one string with another without any error-checking.C programmers use typedef
statements to achieve a modest code-size reduction.
C | C++ |
---|---|
struct Foo my_foo; |
Foo my_foo; |
union Bar my_bar; |
Bar my_bar; |
A more common example, demonstrated by the C FILE type, is hiding the details of library code from application programs.
typedef struct { . . . } FILE; |
FILE* fp = fopen("name", "w"); |
fprintf(fp, "x = %f\n", x); |
(a) | (b) | (c) |