简体   繁体   English

如何在C中安全地使用枚举?

[英]How to use enums in C safely?

consider the following example: 考虑以下示例:

typedef enum {Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday} Day;
void DoSomething(Day day){
//some code
}

The problem is that the following code complies: DoSomething(74) . 问题是以下代码符合: DoSomething(74) So how can I check in DoSomething that my parameter is really a Day? 那么如何在DoSomething中查看我的参数真的是一天? (relying on numbers won't work because if I change my enum like that Sunday=7 .... ,I want it to work too, and checking if(day==Sunday || day ==...) looks inefficient). (依靠数字是行不通的,因为如果我改变我的枚举就像那个Sunday=7 ......,我希望它也可以工作,并检查if(day==Sunday || day ==...)看起来效率低下)。

The short answer is you can't. 简短的回答是你不能。

The long answer is you can try to put a "minimum" and a "maximum" member, and check that the value falls in the range between the two... or some other similar trick. 答案很长,你可以尝试设置一个“最小”和“最大”成员,并检查该值是否介于两者之间...或其他类似的技巧。

typedef enum {Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday, Last} Day;
void DoSomething(Day day){
   // if day < Last ...
}

You could put a switch statement in your DoSomething. 您可以在DoSomething中添加switch语句。

switch(day){
case Day.Monday:
     // something
    break
...
default: 
    // ignore or something

If you write DoSomething(74) statement in your code modern compiler generate warning saying DoSomething expect enum but integer is passed. 如果在代码中编写DoSomething(74)语句,现代编译器会生成警告,说DoSomething期望枚举但是传递整数。

But if you are passing a value from user input where any value can be passed to DoSomething() then you will have to take care as other advised. 但是,如果您从用户输入传递一个值,其中任何值都可以传递给DoSomething(),那么您将不得不像其他建议一样小心。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM