[英]Is there any way I can restrict the values which can be take as cases in a 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定义的值,而不能采用任何其他方式。 如果代码确实包含这种用法,我希望在编译本身时抛出错误。 有什么办法吗?
不,在C语言中无法做到这一点。
我能想到的最接近的是启用警告:
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)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.