DMarlon Studio

Lesson 18 · 18 of 20

Enums and typedef · C

Name fixed values with enum in C and create short type names with typedef: a traffic light and the orders at a coffee shop.

C · Enums and typedef in DMarlon Studio: the example's code and its output in the terminal

An `enum` gives names to a set of whole numbers. In enum Light { RED, YELLOW, GREEN }, RED is 0, YELLOW is 1 and GREEN is 2. Code reads better with RED than with a bare 0, and the compiler can warn you when a switch misses a case.

next uses a switch on the enum to follow the traffic light's order: red, green, yellow and back to red. Since the values are numbers, they also work as indexes: light_names[light] looks up the name in an array of strings.

You can choose the values: in SMALL = 1, MEDIUM, LARGE, the following ones carry on counting, so MEDIUM is 2 and LARGE is 3. That is why size_names starts with an empty string at position 0.

`typedef` gives a type another name. Thanks to it you write Size instead of enum ... and Coffee instead of struct .... The struct for Coffee is declared on a single line, and the orders array holds three orders, which the for prints in columns.

Code · main.c

#include <stdio.h>// enum names a set of whole numbers: RED is 0, YELLOW 1, GREEN 2.enum Light { RED, YELLOW, GREEN };// typedef gives a type a short name; values can be chosen.typedef enum { SMALL = 1, MEDIUM, LARGE } Size;  // MEDIUM is 2typedef struct { char name[12]; Size size; double price; } Coffee;enum Light next(enum Light light) {    switch (light) {        case RED:    return GREEN;        case GREEN:  return YELLOW;        default:     return RED;    }}int main(void) {    const char *light_names[] = {"red", "yellow", "green"};    enum Light light = RED;    for (int i = 0; i < 4; i++) {        printf("Light %d: %s\n", light, light_names[light]);        light = next(light);    }    const char *size_names[] = {"", "small", "medium", "large"};    Coffee orders[] = {{"Latte", MEDIUM, 2.10}, {"Espresso", SMALL, 1.40},                       {"Mocha", LARGE, 2.60}};    for (int i = 0; i < 3; i++)        printf("%-9s %-7s %.2f\n", orders[i].name,               size_names[orders[i].size], orders[i].price);    return 0;}

Output · cc main.c -o main && ./main

Light 0: red
Light 2: green
Light 1: yellow
Light 0: red
Latte     medium  2.10
Espresso  small   1.40
Mocha     large   2.60

Key points

  • enum names whole-number values: the first is 0.
  • You can set a value, SMALL = 1; the next ones carry on.
  • An enum works well in a switch and as an index.
  • typedef creates a short name for a type.
  • With typedef struct { ... } Name; you no longer write struct.

Exercise

Add an enum Milk { WHOLE, SKIMMED, OAT } and a milk field in Coffee, and print each order's milk too.