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?
A common convention for this is to do something like this:
Then you can check for
(t < num_types).If you subsequently add more enums, e.g.
then
num_typesis automatically updated and your error checking code doesn’t need to change.