Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an enum variable is valid?

Tags:

c

enums

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?

like image 725
mustafa Avatar asked Feb 06 '12 14:02

mustafa


People also ask

Can == be used on enum?

equals method uses == operator internally to check if two enum are equal. This means, You can compare Enum using both == and equals method.

How do you check if enum contains a value or not?

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 .


1 Answers

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.

like image 120
Paul R Avatar answered Sep 30 '22 17:09

Paul R