C Enums
An enumeration (enum) is a type whose values are a fixed list of names, such as the days of the week, the levels of a game or the states of a traffic light. Names make the code easier to read than plain numbers.
Declaring an enum
#include <stdio.h>
enum Level { LOW, MEDIUM, HIGH };
int main(void) {
enum Level fan = MEDIUM;
printf("LOW = %d, MEDIUM = %d, HIGH = %d\n", LOW, MEDIUM, HIGH);
if (fan == MEDIUM) {
printf("The fan is at medium speed.\n");
}
return 0;
}LOW = 0, MEDIUM = 1, HIGH = 2 The fan is at medium speed.
Each name stands for a whole number. The first is 0 and each next one is 1 more, unless you choose the values yourself.
Choosing the values
#include <stdio.h>
enum Month { JAN = 1, FEB, MAR, APR };
enum HttpStatus { OK = 200, NOT_FOUND = 404, SERVER_ERROR = 500 };
int main(void) {
printf("MAR is month %d\n", MAR);
printf("Not found is %d\n", NOT_FOUND);
return 0;
}MAR is month 3 Not found is 404
Enums with switch
An enum and a switch fit together well. With -Wall the compiler even warns when a switch forgets one of the enum's names:
#include <stdio.h>
typedef enum { RED, YELLOW, GREEN } Light;
const char *action(Light l) {
switch (l) {
case RED: return "stop";
case YELLOW: return "get ready";
case GREEN: return "go";
}
return "?";
}
int main(void) {
for (Light l = RED; l <= GREEN; l++) {
printf("%d: %s\n", l, action(l));
}
return 0;
}0: stop 1: get ready 2: go
Printing the names
C cannot print an enum's name directly; printf sees only the number. A common trick is an array of strings in the same order:
#include <stdio.h>
typedef enum { MON, TUE, WED, THU, FRI, SAT, SUN } Day;
static const char *dayNames[] = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
int main(void) {
Day today = WED;
printf("Today is %s.\n", dayNames[today]);
printf("The weekend starts on %s.\n", dayNames[SAT]);
return 0;
}Today is Wednesday. The weekend starts on Saturday.
enum or #define?
A list of related constants could also be written with #define RED 0, #define YELLOW 1 and so on. An enum is usually better:
- the names are grouped under one type, so a function parameter of type
Lighttells the reader which values make sense; - the compiler numbers the values for you, so adding one in the middle cannot create duplicates by mistake;
- the compiler can warn when a
switchmisses a value, and debuggers show the names.
Keep in mind that C does not stop you from storing any number in an enum variable: Light l = 7; compiles. The type documents your intention; it does not enforce it.
Practice exercises
- Make an enum for the four seasons and print a sentence for each with a
switch. - Make an enum for coffee sizes with prices as values (SMALL = 120, MEDIUM = 150, LARGE = 180) and add up an order.
- Remove one case from the traffic light
switchand read the warning.