枚举是由整数常量组成的用户定义数据类型,每个整数常量都有一个名称。关键字enum用于定义枚举数据类型。
如果使用enum而不是int或string/ char*,则可以增加编译时检查,并避免错误传入无效的常量,并记录哪些值可以合法使用。
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); }
主要功能定义如下(例如):
int main(){ enum color chosenColor; printf("Enter a number between 0 and 2"); scanf("%d", (int*)&chosenColor); printColor(chosenColor); return 0; }
(此示例使用从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]); }
使用范围检查的同一示例:
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]); }