简体   繁体   中英

Better enums in C (Arduino)

I thought the below was a neat way to implement enums in 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. 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. 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.

Types in C are always global and never nested. So there is no way to have scoped constants.

Thus the :: notation is not allowed in C, it is not part of the syntax. Eg your constants as waitPackage are visible as such everywhere.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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