An enum groups related integer constants under a named type. Names are easier to understand than scattered numeric codes and let variables and parameters express a limited set of states.
#include <stdio.h>
enum TrafficLight {
LIGHT_RED,
LIGHT_YELLOW,
LIGHT_GREEN
};
const char *light_message(enum TrafficLight light) {
switch (light) {
case LIGHT_RED:
return "stop";
case LIGHT_YELLOW:
return "prepare";
case LIGHT_GREEN:
return "go";
default:
return "unknown";
}
}
int main(void) {
enum TrafficLight current = LIGHT_GREEN;
printf("%s\n", light_message(current));
return 0;
}Without explicit values, the first enumerator starts at 0 and later values increase by one. You may assign an integer explicitly; the next implicit value continues from it. Enumerators are integer constants, but enum-typed variables still communicate intent.
#include <stdio.h>
enum LogLevel {
LOG_DEBUG = 10,
LOG_INFO = 20,
LOG_WARNING = 30,
LOG_ERROR = 40
};
int main(void) {
enum LogLevel level = LOG_WARNING;
if (level >= LOG_WARNING) {
puts("show an alert");
}
printf("numeric value: %d\n", level);
return 0;
}A C enum does not automatically convert a value to its name. To display text such as LIGHT_GREEN, write a switch function or a name table.
KNOWLEDGE QUIZ
QUESTION
Without explicit assignments, what is LIGHT_YELLOW's integer value?
KNOWLEDGE QUIZ
QUESTION
Why use enum TrafficLight instead of bare integers?