I have an enum:
enum myenum{
typeA,
typeB,
typeC
} myenum_t;
Then, a functions is to be called with an enum parameter:
int myfunction(myenum_t param1)
{
switch(param1)
{
case typeA:
case typeB:
case typeC:
//do the work
break;
default:
printf("Invalid parameter");
}
return 0;
}
But, as myenum_t
grows with more and more values, myfunction
doesn't seem so elegant.
Is there a better way to check if an enum is valid or not?
equals method uses == operator internally to check if two enum are equal. This means, You can compare Enum using both == and equals method.
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 .
A common convention for this is to do something like this:
typedef enum {
typeA,
typeB,
typeC,
num_types
} myenum_t;
Then you can check for (t < num_types)
.
If you subsequently add more enums, e.g.
typedef enum {
typeA,
typeB,
typeC,
typeD,
typeE,
num_types
} myenum_t;
then num_types
is automatically updated and your error checking code doesn't need to change.
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