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