有没有什么办法可以限制在switch语句中可以采用的值?

时间:2014-01-12 09:46:58

标签: c gcc compilation switch-statement

有什么方法可以限制可以在switch语句中作为案例的值?

比方说,我在C

中有这个代码
#include "stdio.h"
#include "stdlib.h"

#define FRIDAY    (5)

typedef enum {  
    SUNDAY, 
    MONDAY, 
    TUESDAY, 
    WEDNESDAY, 
    THURSDAY 
}e_case_values;

int main()
{
    e_case_values case_value = SUNDAY;

    switch(case_value)
    {
        case SUNDAY:
            printf("The day is Sunday");
        break;

        case MONDAY:
            printf("The day is Monday");

        case FRIDAY:
            printf("The day is Friday");

        default:
            printf("Some odd day");
    }

    return EXIT_SUCCESS;
}

现在,我的目标是switch语句只能获取由枚举e_case_values定义的值,而不能通过任何其他方式。如果代码确实包含这样的用法,我希望在编译期间抛出错误。有没有办法这样做?

2 个答案:

答案 0 :(得分:3)

不,在C中无法做到这一点。

答案 1 :(得分:3)

我能想到的最接近的是启用警告:

main.cpp:27:9: warning: case value '5' not in enumerated type 'e_case_values' 
                        [-Wswitch]

         case FRIDAY:

然后,您可以-Werror=switch仅将此警告视为错误。它不会影响其他警告。 问题当然是您在错误消息中看到5而不是FRIDAY我没有看到#define FRIDAY (5)