简体   繁体   中英

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. 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.

So any value of that integral type is a valid value for your 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. 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.

If the enum has only sequential values, some programs have a max enum value for their enum. These can either have explicit values, or have the implicit values which will always start from 0 and go up sequentially. 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.

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");
}

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