Simple Enumeration
suggest changeAn enumeration is a user-defined data type consists of integral constants and each integral constant is given a name. Keyword enum
is used to define enumerated data type.
If you use enum
instead of int
or string/ char*
, you increase compile-time checking and avoid errors from passing in invalid constants, and you document which values are legal to use.
Example 1
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(){ enum color chosenColor; printf("Enter a number between 0 and 2"); scanf("%d", (int*)&chosenColor); printColor(chosenColor); return 0; }
Example 2
(This example uses designated initializers which are standardized 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]); }
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents