在C语言中,枚举类型(enum)可以用来定义一组具有固定取值范围的常量。枚举类型的使用方式如下:
enum Weekday {
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
};
enum Weekday today = Tuesday;
switch(today) {
case Monday:
printf("Today is Monday.\n");
break;
case Tuesday:
printf("Today is Tuesday.\n");
break;
// 其他case...
}
枚举类型的取值默认从0开始,依次递增。也可以手动指定枚举常量的值:
enum Color {
Red = 1,
Green = 2,
Blue = 4
};
枚举类型可以简化代码的阅读和维护,使得程序更加清晰易懂。