tags:

views:

89

answers:

5

is there an easy way in C to figure out if an enumeration contains a certain element?

+10  A: 

No. C does not have reflection, and enums are basically just scoped, related, integral constants.

Matthew Flaschen
A: 

Basically, the only option is to grep the file where it's declared.

Chuck
+1  A: 

Actually, maybe.

If you have an enum like: ErrorType { BAD_ERROR = 0, REALLY_BAD_ERROR=1, MAXNUM_ERROR }

Then whenever you get an ErrorType, you can check to see that:

int error;
error = REALLY_BAD_ERROR;
error = 6;
if (error < MAXNUM_ERROR) { /* error is valid */ }

Somewhat of a hack though. Only works with sequential enums (if REALLY_BAD_ERROR were 3 and there was no 2, this would break).

bowenl2
+2  A: 

Not in general case. Some people adopt a convention along the lines of:

enum xxx
{
    xxx_min = 0,
    xxx_a   = 0,
    xxx_b   = 1,
    ...
    xxx_z   = 42,
    xxx_max = 42
};

#define check_enum(e,n) assert((n)>= e##_min && (n) <= e##_max)

This of course assumes that the enumeration values are continuous, and requires a lot of discipline from the developer(s), so might or might not be a good idea depending on the context.

Nikolai N Fetissov
+2  A: 

Yes there is a way to check if its part of enum, provided the enum is initialised.

enum value
{
ENUM_MIN = 0,  
.
.
.
.
.
ENUM_MAX  
};

suppose you have int x = -1;

if(x>ENUM_MIN && x< ENUM_MAX)
printf(" Part of enum");

This wont work in the below case:

enum value
{
ENUM_MIN = 0,
ENUM_TWO =2,
.
.
.
ENUM_MAX
};

if the value of x is equal to 1, then you cant use the above solution.

Praveen S