Making a type definition for user defined types

It is very often convenient to associate a name with a type, so that the programmer can subsequently declare variables to be of this named type. Type definitions can be made within the main program or within a function. The scope rules are similar to those for variables. The type definition is introduced by the word typedef. Within a typedef user-chosen identifiers can be equivalenced to type definitions, as in the examples below:
/* Some user defined types */

enum Rainbow {red,orange,yellow,green,blue,indigo,violet};

struct person {
                  int age;
                  char sex;
               };

union car_part {
        struct engine ept;
        struct seats spt;
        struct radio rpt;
    };

/* Various kinds of typedef */

typedef enum Rainbow Spectrum;  /* Spectrum to enum Rainbow */

typedef int WholeNum;           /* WholeNum to int */

typedef struct person Employee; /* Employee to person */

typedef union car_part CARPART;

/* Some variable declarations */

Spectrum S1, S2;	/*Variables S1 and S2 of type Spectrum */
WholeNum D1, D2;	/*Variables D1 and D2 of type WholeNum */
Various conventions for identifying names of types are used. Perhaps the most common is to use upper case identifiers for types, but this is merely a coding standard, not a requirement of C.

Exercises on this section.


Next - Example of using structs.

Back to Contents page.