Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a value is defined in an C enum?

Tags:

c

enums

Assuming that I have this:

enum { A = 0x2E, B = 0x23, C = 0x40 }

it's possible check if x is defined into enum?

I'm doing it manually: int isdef = (x == A || x == B || x == C); But I want to something more dynamic. GCC-extensions are welcome too.

like image 252
Jack Avatar asked Jun 14 '12 20:06

Jack


People also ask

How do you check if a value is defined in an enum?

Enum. IsDefined is a check used to determine whether the values exist in the enumeration before they are used in your code. This method returns a bool value, where a true indicates that the enumeration value is defined in this enumeration and false indicates that it is not. The Enum .

How do you check if a string is present in enum?

The EnumUtils class has a method called isValidEnum whichChecks if the specified name is a valid enum for the class. It returns a boolean true if the String is contained in the Enum class, and a boolean false otherwise.

Can you index an enum in C?

Yes, but unlike an enum, you have to specify a type for the values. You also have to make sure the index won't be higher than the number of cells.


2 Answers

To expand on the accepted answer, use X-macros to build your enum and array from the same data using the preprocessor.

/* Only need to define values here. */
#define ENUM_VALUES \
    X(A, 0x2E)  \
    X(B, 0x23)  \
    X(C, 0x40)

/* Preprocessor builds enum for you */
#define X(a, b) a = b,
    enum {
        ENUM_VALUES
    };
#undef X

/* Preprocessor builds array for you */
#define X(a, b) a,
    const int E[] = {
        ENUM_VALUES
    };
#undef X

/* Copied from accepted answer */
int isEnum(int x)
{
    for(int i=0; i<sizeof(E);i++)
    {
        if(E[i] == x){ return 1; }
    }
    return 0;
}
like image 174
AaronDanielson Avatar answered Oct 30 '22 13:10

AaronDanielson


The easiest way to do this is:


enum {
    MODE_A,
    MODE_B,
    MODE_C
};

int modeValid(int mode)
{
    int valid = 0;

    switch(mode) {
        case MODE_A:
        case MODE_B:
        case MODE_C:
            valid = 1;
    };

    return valid;
}

void setMode(int mode)
{
    if (modeValid(mode)) {
        // Blah, blah
    }
}

int main(void)
{
    setMode(1);   // Okay
    setMode(500); // Error
}
like image 24
Luke Kowald Avatar answered Oct 30 '22 14:10

Luke Kowald