简体   繁体   English

如何验证从文件读取的枚举值?

[英]How do I validate an enum value read from a file?

If I am reading binary values from a file in C, then an integer that is supposed to be a member of an enum can be checked manually by looping through the enum itself and verifying that the integer is one of those values, but this seems like a somewhat tedious process. 如果我从C中的文件读取二进制值,那么可以通过循环遍历枚举本身并验证整数是其中一个值来手动检查应该是枚举成员的整数,但这看起来像一个有点乏味的过程。 If I just cast the read value to the enum, then I assume some kind of runtime error will occur if the value is invalid. 如果我只是将读取值转换为枚举,那么我假设如果值无效将发生某种运行时错误。

Is there a better method of validating the enum than doing a manual check loop? 有没有比使用手动检查循环更好的验证枚举的方法?

Note that in my case, the enum(s) in question do not necessarily have consecutive values, so min/max checking is not a solution. 请注意,在我的情况下,所讨论的枚举不一定具有连续值,因此最小/最大检查不是解决方案。

In C, all enum s are actually integral types. 在C中,所有enum实际上都是整数类型。

So any value of that integral type is a valid value for your enum . 因此,该整数类型的任何值都是enum的有效值。

If you are careful and set up the enum labels so they are consecutive (the default is consecutive from 0), it's a simple case of checking if the value from the file is in that range. 如果你小心并设置enum标签使它们是连续的(默认值是从0开始连续),那么检查文件中的值是否在该范围内是一个简单的例子。 Otherwise, yes, it's tedious. 否则,是的,这很乏味。

enum in C works like an integer, and so it can be forced to any value by any kind of read function taking a pointer, or directly casting it from integer types. C中的enum就像一个整数,所以它可以通过任何类型的读取函数强制转换为任何值,或者直接从整数类型转换它。

If the enum has only sequential values, some programs have a max enum value for their enum. 如果枚举只有连续值,则某些程序的枚举值为max枚举值。 These can either have explicit values, or have the implicit values which will always start from 0 and go up sequentially. 它们可以具有显式值,也可以具有始终从0开始并按顺序上升的隐式值。 This way they can just check the value is in the allowed range (0 to max - 1 ), rather than checking it for every allowed value. 这样他们就可以检查值是否在允许的范围内(0到max - 1 ),而不是检查每个允许的值。

typedef enum foo { 
    foo_a,
    foo_b,
    foo_c,
    foo_max //last
} foo;
int main(void)
{
    foo x = (foo)88; // from somewhere
    if (x >= 0 && x < foo_max)
        printf("valid\n");
    else printf("invalid\n");
}

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

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