3.4. Enumeration Types and Typedef

Here we present another mechanisms for user-defined data types. Like typedef, it is not needed to write any program, but can help with the clarity of a program.

3.4.1. Enumerator

The enum keyword allows a programmer to create a named finite set of elements. The names of the elements of the set are also defined by the programmer.

  • The sole purpose of the enumerator is to increase the clarity of the program.

  • There is no input or output mechanism for enumerators, so the program must have hard coded statements which set the value of the enumerator.

  • Enumerator values are stored as integers, so integers can be used either in setting the value of an enumerator or testing the value of an enumerator.

  • The declaration of an enum defines the elements of the enumerator. It is necessary define a variable to use the enum.

  • By default the values stored for an enum variable is 0 through (N - 1), where the enumerator has N elements. This can be changed, however.

    enum month {Jan, Feb, March, April, May, June, July, Aug, Sept, Oct,
    Nov, Dec};
    
    /* Jan == 0, Feb == 1,... Dec == 11 */
    
    enum month month_due, month_late;
    int input;
    int next_month;
    
    ...
    
    if ( input == 1 ) month_due = Jan;
    
    ...
    
    next_month = (input + 1) % 12;
    month_late = (month)next_month - 1;
    
    ...
    
    if ( month_due == Jan )
       printf( "Your bill is due to be paid in January\n" );
    
    enum cars { ford = 3, dodge, honda = 8, toyota };
       /* dodge == 4, toyota == 9 */
    

3.4.2. Typedef

The typedef keyword allows us to rename a data type to a name that has more meaning to our program.

  • The only purpose of typedef is increased program clarity.

  • typedef can be used to rename any data type including enum and struct definitions, which we will study shortly.

  • The typedef statement may be specified by itself or as part of a enum or struct definition.

  • The typedef defined new name is often the given the same name as the enum or struct definition.

  • Sometimes when typedef is used with an individual data type (char, int, float …), it is done so to make a program more easily ported to another platform. For example, we could typedef a name like fullword to be what ever variable type is 32 bits. Then if needed when porting the program to another platform, the typedef definition can be changed and the data declarations do not need to be modified.

    typedef char   Letter;
    typedef int    Inches;
    typedef double math;
    
    Letter ch;
    Inches height;
    math x;
    
    typedef enum month billing_cycle;
    billing_cycle month_due;
    
    typedef enum day {sun, mon, tue, wed, thu, fri, sat} day;
    day today;
    
    typedef struct date {
       day day_of_week;
       enum month month_of_year;
       int day_of_month;
    } date;
    
    date due_date;