Simple Enumeration
suggest changeAn enumeration defines a distinct type and a set of named integer constants. Use the enum keyword to declare one.
Compared with using unexplained integers, an enum documents the intended values and can help compilers diagnose mistakes. An enum object can still hold a value that does not name one of its enumerators, so validate untrusted input.
Example 1
#include <stdio.h>
enum color{ RED, GREEN, BLUE };
void printColor(enum color chosenColor)
{
const char *color_name = "Invalid color";
switch (chosenColor)
{
case RED:
color_name = "RED";
break;
case GREEN:
color_name = "GREEN";
break;
case BLUE:
color_name = "BLUE";
break;
}
printf("%s\n", color_name);
}
With a main function defined as follows (for example):
int main(void)
{
int input;
printf("Enter a number between 0 and 2: ");
if (scanf("%d", &input) != 1 || input < RED || input > BLUE) {
fputs("Invalid color\n", stderr);
return 1;
}
printColor((enum color)input);
return 0;
}
Example 2
(This example uses designated initializers, which have been standard since C99.)
enum week{ MON, TUE, WED, THU, FRI, SAT, SUN };
static const char* const dow[] = {
[MON] = "Mon", [TUE] = "Tue", [WED] = "Wed",
[THU] = "Thu", [FRI] = "Fri", [SAT] = "Sat", [SUN] = "Sun" };
void printDayOfWeek(enum week day)
{
printf("%s\n", dow[day]);
}
The same example using range checking:
enum week{ DOW_INVALID = -1,
MON, TUE, WED, THU, FRI, SAT, SUN,
DOW_MAX };
static const char* const dow[] = {
[MON] = "Mon", [TUE] = "Tue", [WED] = "Wed",
[THU] = "Thu", [FRI] = "Fri", [SAT] = "Sat", [SUN] = "Sun" };
void printDayOfWeek(enum week day)
{
assert(day > DOW_INVALID && day < DOW_MAX);
printf("%s\n", dow[day]);
}
assert requires <assert.h>. If NDEBUG is defined, that test is removed and an out-of-range day makes dow[day] undefined behavior. Use assert for programmer errors, not as the only check of untrusted input.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents