在C語言中使用枚舉類型在switch case語句中非常方便。首先需要定義一個枚舉類型,然后在switch case中使用這個枚舉類型的值來進(jìn)行判斷。以下是一個簡單的示例:
#include <stdio.h>
enum Weekday {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday};
int main() {
enum Weekday today = Wednesday;
switch (today) {
case Monday:
printf("Today is Monday\n");
break;
case Tuesday:
printf("Today is Tuesday\n");
break;
case Wednesday:
printf("Today is Wednesday\n");
break;
case Thursday:
printf("Today is Thursday\n");
break;
case Friday:
printf("Today is Friday\n");
break;
case Saturday:
printf("Today is Saturday\n");
break;
case Sunday:
printf("Today is Sunday\n");
break;
default:
printf("Invalid day\n");
break;
}
return 0;
}
在上面的示例中,我們首先定義了一個枚舉類型Weekday,包括了每個星期幾的枚舉值。然后在main函數(shù)中定義了一個變量today,并初始化為Wednesday。在switch case語句中,根據(jù)today的值來輸出對應(yīng)的星期幾。
使用枚舉類型在switch case語句中可以使代碼更清晰易讀,枚舉值的名稱可以給代碼增加可讀性,并且可以避免使用魔術(shù)數(shù)值。