在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
};
枚舉類型可以簡化代碼的閱讀和維護,使得程序更加清晰易懂。