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.
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 .
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.
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.
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;
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With