Learn C · lesson 57 of 60 · about 8 minutes
enum
Give names to a fixed set of choices, so code says what it means.
What you'll learn
- Define an enum and use its names
- Know that enum names are numbers underneath
- Use an enum with switch
Is every server up?
The night shift wants to know how each server is doing. For each of the web, db and mail servers, the report reads one line, up, slow or down, and says what it means: db is slow: keep an eye on it, or mail is down: wake the on-call. Anything else counts as down, because a server nobody can read is a server to worry about. Then it gives the worst status of the night, Worst status: slow, or Every server is up. Three fixed choices with names are what an enum is for.
Named choices
Some values can only be one of a few choices: a traffic light is red, amber or green. You could use 0, 1 and 2, but nobody remembers which is which.
An enum names the choices: enum light { RED, AMBER, GREEN };. Underneath they're just ints, starting from 0, so RED is 0, AMBER is 1 and GREEN is 2.
A traffic light
#include <stdio.h>
enum light { RED, AMBER, GREEN };
int main(void) {
enum light now = AMBER;
printf("%d\n", now);
now = GREEN;
if (now == GREEN) printf("Go!\n");
return 0;
}Output
1
Go!enum and switch
Enums and switch go together: one case per choice. You can also choose the numbers yourself, like enum { LOW = 1, HIGH = 10 };, and a typedef saves writing enum every time.
Switching on an enum
#include <stdio.h>
typedef enum { NORTH, EAST, SOUTH, WEST } Direction;
Direction turn_right(Direction d) {
return (d + 1) % 4;
}
const char *name(Direction d) {
switch (d) {
case NORTH: return "north";
case EAST: return "east";
case SOUTH: return "south";
case WEST: return "west";
}
return "?";
}
int main(void) {
Direction d = WEST;
printf("%s\n", name(turn_right(d)));
return 0;
}Output
northBest to worst
typedef enum { UP, SLOW, DOWN } Status; lists the statuses from best to worst, so UP is 0, SLOW is 1 and DOWN is 2. That order does real work: if (s > worst) keeps the worst status so far, and status_names[worst] turns the number back into a word. status_of turns a typed word into a Status with strcmp, and the switch gives each status its own message.
Tip
Enum names are usually written in CAPITALS, like constants, because that's what they are.
Now try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.