Enumerated Types in C

  • An enumerated type is a programmer-defined data type.   The programmer can declare a new data type that doesn't exist in the basic language definition. 

  • Enumerated types represent data where every possible value in the type has a name.
    Examples:
    Type
    Values
    Traffic signal colors
    red, green, yellow
    Compass directions
    north, south, east, west
    U.S. coins
    penny, nickel, dime, quarter, dollar
    Playing card suits
    hearts, clubs, spades, diamonds

  • Because every possible value of the type can be named, we say the data are enumerable, and call the type an enumerated type. (As distinguished from integer, for example, which has infinite possible values).

  • Enumerated types enable the programmer to refer to these values by their names instead of arbitrary numeric codes.   This promotes readability and reduces errors.

  • The enum  keyword in C is used to declare an enumerated type and all possible values are listed in braces:
    typedef enum
    {
        north,
        east,
        south,
        west
    }
    compass_direction;

    This example defines an enumerated type called compass_direction, which can be assigned one of four enumerated values: north, east, south, or west.

  • In order to use the enumerated type, one makes a variable declaration:
    compass_direction current_heading;
    current_heading = west;
    This example declares a variable called current_heading of the enumerated compass_direction type, and assigns it the value west.

  • These kind of variables can mostly be used like other variables. You can compare them or pass them as parameters or return them from functions.

    if (current_heading == west)
    {
    printf("You won't see any penguins that way");
    }


  • Unfortunately there isn't an easy way to read them from the keyboard or print them.  Enumerated values are not strings and can't be read, printed, or manipulated like strings.

  • Unfortunately the compiler doesn't check that a valid value is assigned to an enum variable, so  current_heading = 17; is allowed even though it's clearly wrong.  (Note: Other languages have solved these problems).

  • View a complete example program.