Say a traffic light can be red, yellow or green. You could use 0, 1 and 2 – but who remembers which is which? An enum (enumeration) gives each number a name:
#include <stdio.h>
enum Light { RED, YELLOW, GREEN };
int main() {
enum Light now = GREEN;
if (now == GREEN) {
printf("Go!\n");
}
printf("GREEN is really the number %d\n", now);
return 0;
}Output
Go! GREEN is really the number 2
C numbers the names for you, starting at 0: RED is 0, YELLOW is 1, GREEN is 2.
enum and switch
Enums and switch fit together perfectly:
#include <stdio.h>
typedef enum { NORTH, EAST, SOUTH, WEST } Direction;
void describe(Direction d) {
switch (d) {
case NORTH: printf("Up\n"); break;
case EAST: printf("Right\n"); break;
case SOUTH: printf("Down\n"); break;
case WEST: printf("Left\n"); break;
}
}
int main() {
describe(SOUTH);
describe(EAST);
return 0;
}Output
Down Right
Choosing the numbers
You can pick the numbers yourself. The ones after continue counting up:
#include <stdio.h>
enum Month { JAN = 1, FEB, MAR, APR };
int main() {
printf("%d %d %d\n", JAN, FEB, APR);
return 0;
}Output
1 2 4
Remember: Use an
enumwhenever a value can only be one of a few named choices.