如何保护枚举分配 [英] How to protect enum assignment

查看:58
本文介绍了如何保护枚举分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想防止无效的值枚举分配.我知道如果我什至赋值不是枚举也将起作用.示例:

I want to prevent invalid value enum assignment. I know if i even assign value that is not in enum it will work. Example:

enum example_enum
{
    ENUM_VAL0,
    ENUM_VAL1,
    ENUM_VAL2,
    ENUM_VAL3
};

void example_function(void)
{
  enum example_enum the_enum = ENUM_VAL3; // correct
  the_enum = 41; // will work
  the_enum = 0xBADA55; // also will work
  bar(the_enum); // this function assumes that input parameter is correct
}

是否有一种简单,有效的方法来检查对枚举的分配是否正确?我可以按功能测试值

Is there easy, efficient way to check if assignment to enum is correct? I could test value by function

void foo(enum example_enum the_enum)
{
  if (!is_enum(the_enum))
    return;

  // do something with valid enum
}

我可以通过以下方式解决此问题:

I could resolve this in following way:

static int e_values[] = { ENUM_VAL0, ENUM_VAL1, ENUM_VAL2, ENUM_VAL3 };
int is_enum(int input)
{
  for (int i=0;i<4;i++)
    if (e_values[i] == input)
      return 1;
  return 0;
}

对我来说,我的解决方案效率低下,如果我有更多的枚举和枚举中的更多值,该怎么写?

For me, my solution is inefficient, how can i write this if i have more enums and more values in enums?

推荐答案

只要 enum 是连续的,就可以执行以下操作:

As long as the enum is continuous one can do something like this:

static int e_values[] = { ENUM_VAL0, ENUM_VAL1, ENUM_VAL2, ENUM_VAL3, ENUM_VAL_COUNT };

int is_enum(int input) { return 0 <= input && input < ENUM_VAL_COUNT; }

另一种选择是不预先验证枚举值,而是在代码检测到无效值时出错:

Another alternative is to not validate the enum value beforehand, but error out once the code detects an invalid value:

switch(input) {
    case ENUM_VAL0: ... break;
    case ENUM_VAL1: ... break;
    ...
    default:
        assert(0 && "broken enum"); 
        break;
} 

但是无法强制 enum 值完全不超出C的范围.如果要保护 enum 避免摆弄是将值隐藏在 struct 中,然后具有操作 struct 的功能.通过 .h 文件中的前向声明和 .c 文件中的实现,可以将函数和 struct 实现隐藏在用户面前:

But there is no way to enforce that the enum value doesn't go out of the range at all in C. The best you can do if you want to secure the enum against fiddling is to hide the value away in a struct and then have functions to manipulate the struct. The function and struct implementation can be hidden away from the user via a forward declaration in the .h file and the implementation in the .c file:

struct example_t {
     enum example_enum value;
}

void example_set_val0(example_t* v) { v->value = ENUM_VAL0; }

这篇关于如何保护枚举分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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