Check if an int value is within valid range of enum?
Suppose I have defined an enum:
Code:
enum myEnum { Code:
if (value != VAL_A && value != VAL_B && value != VAL_C ....) |
well, you could use an int array of valid values.
Iterate and check. but then you'd still need to hard-code the values twice if you wanted the enums which leaves room for bugs. can't think of a neat way meself keeping the enums. |
Well, first, how would your input stream creator know what values had been used in your enumeration type? In other words, why would you be using an enumeration type to parse an input stream?
The obvious solution would be to set up an array, initialize it to your enumeration values, sort it, and do a binary search to find a match, if any. Note, however, that there is no restriction on the values assigned to enumeration types, so, for example, this is a perfectly valid enumeration: Code:
enum myEnum { So, again, I don't think you should compare any data stream with an enumeration type. Just use a array of valid input values and search it. Aside: If you're using C++, there are several templates in the standard template library to make this problem fairly easy. |
I'm using enum for a config option. If this option has some weird value, the program would not function properly. I use switch sentences for handling these options, so the program eventually finds out the value is wrong, but this could happen only when the switch block gets executed, which could be after a long time. I'd like to warn user of this shortly after the program is started.
I'm writing in C, not C++. The user knows which numbers are valid, but there is always a possibility of a human mistake or config file corruption ... Quote:
1) Determine what length should that array have. I don't know how to get the enum length, sizeof(anyEnum) returns 4. 2) Initialize that array to enum values. Without explicitly naming every value of course. |
noddy example:
Code:
#include <stdio.h> |
Thanks, funny output by the way (yuk:D )
It is however, not exactly what I meant. I need enum, because after I'd read and check the value, I'd like to operate only with labels, not numbers and not arrays, because labels tell you much more. I'd like to declare all values only in enum. Then I would use for example something like you suggested, but all the values and length of array should be determined automatically so I will have to change only the enum definition when I decide to change/add/remove an option. Is this possible in C? |
Have you considered using struct instead of enum?
This code seems to work: Code:
$ cat test5.c It gets a little trickier if not all your struct elements are the same type, but remains, I think, workable. |
All times are GMT -5. The time now is 01:22 AM. |