How to check if an enum variable is valid?

前端 未结 7 1081
执笔经年
执笔经年 2021-01-11 11:07

I have an enum:

enum myenum{
  typeA,
  typeB,
  typeC
} myenum_t;

Then, a functions is to be called with an enum parameter:



        
7条回答
  •  余生分开走
    2021-01-11 11:59

    A common convention for this is to do something like this:

    typedef enum {
      typeA,
      typeB,
      typeC,
      num_types
    } myenum_t;
    

    Then you can check for (t < num_types).

    If you subsequently add more enums, e.g.

    typedef enum {
      typeA,
      typeB,
      typeC,
      typeD,
      typeE,
      num_types
    } myenum_t;
    

    then num_types is automatically updated and your error checking code doesn't need to change.

提交回复
热议问题