C Enums
Numbers like 0, 1, and 2 say nothing about what they mean. An enum is a list of named constants, each standing for a whole number.
Names that count from zero
GREEN is the second name, so it holds 1. The output is 1.
#include <stdio.h>
enum Color { RED, GREEN, BLUE };
int main() {
enum Color pick = GREEN;
printf("%d\n", pick);
return 0;
}Names with set values
Each size carries a set value, and LARGE is set to 3. The output is 3.
#include <stdio.h>
enum Size { SMALL = 1, MEDIUM = 2, LARGE = 3 };
int main() {
enum Size pick = LARGE;
printf("%d\n", pick);
return 0;
}Choose with a switch
The stored day is TUE, so the switch picks its case. The output is Tuesday.
#include <stdio.h>
enum Day { MON, TUE, WED };
int main() {
enum Day today = TUE;
switch (today) {
case MON:
printf("Monday\n");
break;
case TUE:
printf("Tuesday\n");
break;
case WED:
printf("Wednesday\n");
break;
default:
printf("Other day\n");
break;
}
return 0;
}Example
#include <stdio.h>
enum Level { BEGINNER, INTERMEDIATE, ADVANCED };
int main() {
enum Level level = ADVANCED;
printf("Level: %d\n", level);
if (level == ADVANCED) {
printf("Top level.\n");
}
return 0;
}Key points
- enum lists names that stand for whole numbers.
- The first name has the value 0, the next has 1, and so on.
- enum Color { RED, GREEN, BLUE }; names three colors.
- A value can be set with =. enum Size { SMALL = 1, MEDIUM = 2, LARGE = 3 }; starts at 1.
- An enum variable holds one of the named values.
- printf with %d prints the number behind a name.
- Use an enum when a value has a small set of clear choices.
Three levels count from zero, so ADVANCED holds 2. The output prints that number, then a line for the top level.
Note
Enum names share one list, so keep each name distinct.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What value does the second name in an enum hold when no values are set?