C/C++ Arena

Step 5 of 7

enum

Many values come from a small, fixed set: a traffic light is red, yellow or green; a player is on one of two sides. You could use plain ints (0, 1, 2), but then the code is full of magic numbers. An enum gives each value a name:

#include <stdio.h>

enum Light { RED, YELLOW, GREEN };

const char *action(enum Light l) {
    switch (l) {
        case RED:
            return "stop";
        case YELLOW:
            return "slow down";
        case GREEN:
            return "go";
    }
    return "?";
}

int main(void) {
    enum Light now = YELLOW;
    printf("%s\n", action(now));
    printf("%d %d\n", RED, GREEN);
    return 0;
}
slow down
0 2

How enums work

The names are integer constants. By default the first is 0 and each next one is one more, so RED is 0, YELLOW 1, GREEN 2. You can set values explicitly: enum Http { OK = 200, NOT_FOUND = 404 };.

if (l == GREEN) reads far better than if (l == 2), and if the list changes, the names still mean the right thing.

Enums and switch

switch over an enum is a natural pairing. Compilers can even warn (-Wswitch) when a switch forgets one of the enum's values, which catches bugs when a new value is added later.

Returning strings

The function returns const char * pointing at string literals. Literals live for the whole program, so returning them is safe (unlike returning a local array). The const is there because literals must not be modified.

C doesn't stop you from storing any int in an enum variable, which is why a final fallback like return "?" is good practice.

Your turn: write const char *weapon_name(enum Weapon w) that returns "rifle", "pistol", "knife" for the three enum values and "?" otherwise.

Previous: Arrays of structs Next: typedef