326 Chapter 14 More on Data Types
To define a new type name with typedef, follow these steps:
- Write the statement as if a variable of the desired type were being declared.
- Where the name of the declared variable would normally appear, substitute the
new type name. - In front of everything, place the keyword typedef.
As an example of this procedure, to define a type called Dateto be a structure contain-
ing three integer members called month,day,and year,you write out the structure defi-
nition, substituting the name Datewhere the variable name would normally appear
(before the last semicolon). Before everything, you place the keyword typedef:
typedef struct
{
int month;
int day;
int year;
} Date;
With this typedefin place, you can subsequently declare variables to be of type Date,
as in
Date birthdays[100];
This defines birthdaysto be an array containing 100 Datestructures.
When working on programs in which the source code is contained in more than one
file (as described in Chapter 15, “Working with Larger Programs”), it’s a good idea to
place the common typedefs into a separate file that can be included into each source
file with an #includestatement.
As another example, suppose you’re working on a graphics package that needs to deal
with drawing lines, circles, and so on.You probably will be working very heavily with
the coordinate system. Here’s a typedefstatement that defines a type named Point,
where a Pointis a structure containing two floatmembers xand y:
typedef struct
{
float x;
float y;
} Point;
You can now proceed to develop your graphics library, taking advantage of this Point
type. For example, the declaration
Point origin = { 0.0, 0.0 }, currentPoint;
defines originand currentPointto be of type Pointand sets the xand ymembers of
originto 0.0.