简体   繁体   English

C中更好的枚举(Arduino)

[英]Better enums in C (Arduino)

I thought the below was a neat way to implement enums in C. 我认为以下是在C中实现枚举的一种好方法。

struct states
{
  enum
  {
    waitPackage,
    waitReference,
    waitData
  };

}state;

This adds some type safety and I can also acces each member through state.XXX which I think is a lot more neat than prepend all the names of the enum items, and access the members in a fashion like state_XXX. 这增加了某种类型的安全性,我还可以通过state.XXX来加入每个成员,我认为这比在枚举项的所有名称前添加整齐得多,并且可以像state_XXX这样访问成员。 Or what do you think, have I missed something? 还是您觉得我错过了什么?

However, I cant use the enum above in a switch-case statement as the compiler says that state isn't a constant. 但是,我不能在switch-case语句中使用上面的枚举,因为编译器说状态不是常量。 Is there a way to tell the compiler that I don't intend to change the members of the enum ot it could be used in switch-case? 有没有办法告诉编译器我不打算更改枚举的成员,否则它可能会在切换情况下使用? Or another way to accomplish what I would like here? 或者以另一种方式来实现我在这里想要的?

In a C++ I solved it by placing the enums in namespaces but thats a not an option here. 在C ++中,我通过将枚举放在名称空间中来解决它,但这不是这里的选择。

Types in C are always global and never nested. C中的类型始终是全局的,并且从不嵌套。 So there is no way to have scoped constants. 因此,没有办法拥有范围常量。

Thus the :: notation is not allowed in C, it is not part of the syntax. 因此, ::表示法在C中是不允许的,它不是语法的一部分。 Eg your constants as waitPackage are visible as such everywhere. 例如, waitPackage等常量在waitPackage都可见。

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

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