温馨提示×

如何在C语言的switch case中使用枚举

小樊
152
2024-06-13 22:07:43
栏目: 编程语言

在C语言中使用枚举类型在switch case语句中非常方便。首先需要定义一个枚举类型,然后在switch case中使用这个枚举类型的值来进行判断。以下是一个简单的示例:

#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函数中定义了一个变量today,并初始化为Wednesday。在switch case语句中,根据today的值来输出对应的星期几。

使用枚举类型在switch case语句中可以使代码更清晰易读,枚举值的名称可以给代码增加可读性,并且可以避免使用魔术数值。

0