Node:typedef, Next:Questions 19, Previous:struct and union, Up:More data types
typedef
You can define your own data types in C with the typedef
command,
which may be written inside functions or in global scope. This
statement is used as follows:
typedef existing_type new_type;
You can then use the new type to declare variables, as in the following
code example, which declares a new type called my_type
and declares
three variables to be of that type.
#include <stdio.h> /* To shorten example, not using argp */ int main (int argc, char *argv[], char *envp[]) { typedef int my_type; my_type var1, var2, var3; var1 = 10; var2 = 20; var3 = 30; return 0; }
The new type called my_type
behaves just like an integer.
Why, then, would we use it instead of integer
?
Actually, you will seldom wish to rename an existing data type.
The most important use for typedef
is in renaming structures and unions,
whose names can become long and tedious to declare otherwise.
We'll investigate structures and unions in the next chapter.
(See Data structures.)