The typedefStatement 325
The typedefStatement
C provides a capability that enables you to assign an alternate name to a data type.This is
done with a statement known as typedef.The statement
typedef int Counter;
defines the name Counterto be equivalent to the C data type int.Variables can subse-
quently be declared to be of typeCounter, as in the following statement:
Counter j, n;
The C compiler actually treats the declaration of the variables jand n, shown in the
preceding code, as normal integer variables.The main advantage of the use of the
typedefin this case is in the added readability that it lends to the definition of the
variables. It is clear from the definition of jand nwhat the intended purpose of these
variables is in the program. Declaring them to be of type intin the traditional fashion
would not have made the intended use of these variables at all clear. Of course, choosing
more meaningful variable names would have helped as well!
In many instances, a typedefstatement can be equivalently substituted by the appro-
priate #definestatement. For example, you could have instead used the statement
#define Counter int
to achieve the same results as the preceding statement. However, because the typedefis
handled by the C compiler proper, and not by the preprocessor, the typedefstatement
provides more flexibility than does the #definewhen it comes to assigning names to
derived data types. For example, the following typedefstatement:
typedef char Linebuf [81];
defines a type called Linebuf,which is an array of 81 characters. Subsequently declaring
variables to be of type Linebuf, as in
Linebuf text, inputLine;
has the effect of defining the variables textand inputLineto be arrays containing 81
characters.This is equivalent to the following declaration:
char text[81], inputLine[81];
Note that, in this case,Linebufcould nothave been equivalently defined with a #define
preprocessor statement.
The following typedefdefines a type name StringPtrto be a charpointer:
typedef char *StringPtr;
Va r iables subsequently declared to be of type StringPtr, as in
StringPtr buffer;
are treated as character pointers by the C compiler.