Enumerated type

Enumerated type#

enum { ON, OFF, BLINKING } led_state;

typedef enum { RED, GREEN, BLUE, LEDOFF } Color;
Color led_color_top = BLUE, led_color_right = LEDOFF;

Color led_color_bottom = OFF;
// Even `OFF` does not belong to the `Color`, C does not warn. 😕
// These identifiers behave like constants.

typedef enum { CLUBS, DIAMONDS, HEARTS, SPADES, SUIT_COUNT } CardSuit;
// `SUIT_COUNT` is an idiom to automatically get the number of enumerated values, in case we need to use it in our code

CardSuit cards[13];

typedef enum { LOW = 10, MEDIUM = 50, HIGH = 100 } SensorLevel;

Using typedef we can use our enumeration as a type and declare variables somewhere else than in the global declaration area.

enumerated type

a data type consisting of a set of named values called enumerators of the type. The enumerator names are usually identifiers that behave as constants.

Tip

Use CamelCase for enum types.

Activity 26

Implement the following state machine for a coffee machine. Use an enum for the states. Simulate the states using console messages like brewing.

        stateDiagram-v2
    [*] --> IDLE

    IDLE --> BREWING: "s" pressed
    BREWING --> DONE: after 2s
    DONE --> IDLE: "r" pressed
    DONE --> [*]: "e" pressed