如何检查是否一个枚举变量是有效的? [英] How to check if an enum variable is valid?

查看:134
本文介绍了如何检查是否一个枚举变量是有效的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个枚举:

enum myenum{
  typeA,
  typeB,
  typeC
} myenum_t;

然后,功能是用一个枚举参数来调用:

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

int myfunction(myenum_t param1)
{
  switch(param1)
  {
    case typeA:
    case typeB:
    case typeC:
      //do the work
      break;

    default:
      printf("Invalid parameter");
  }
  return 0;
}

不过,为 myenum_t 的增长越来越多的价值, myfunction的似乎不那么优雅。

But, as myenum_t grows with more and more values, myfunction doesn't seem so elegant.

有没有更好的方法来检查,如果一个枚举是否有效?

Is there a better way to check if an enum is valid or not?

推荐答案

有关这方面的一个共同的约定是做这样的事情:

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

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

然后你可以检查(T< num_types)。

如果您随后添加更多的枚举,例如

If you subsequently add more enums, e.g.

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

然后 num_types 自动更新,你的错误检查code并不需要改变。

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

这篇关于如何检查是否一个枚举变量是有效的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆