Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimized way to check the value of a variable with enum members value

Tags:

c++

c

enums

Hello I have the code below:

enum {a, b, c, d, ..., z} abc;

int main()
{
  int val = 20;
  if (val == a || val == b ||val == c||val == d..... || val == z)
  {
    /*Do something*/
  }
}

Is there any other way so that we can skip the OR operation because if there are 1000s of enum members then how can we do ahead with checking with all members. Please help.

like image 669
Rasmi Ranjan Nayak Avatar asked Oct 17 '12 06:10

Rasmi Ranjan Nayak


People also ask

How do you check if a value is a valid 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.

How do you check if at least one enum value is equal to a variable within an IF condition?

if (randomValue & (Values. Value1 | Values. Value2) > 0) { //... } You can use an array (nicer if you have predefined sets of values you want to search for).


2 Answers

A modern compiler should just be able to optimize such code if, as in your case, the value of the expression is known at compile time. For readability and error checking I think that using a switch would be better:

switch (val)  {
 case a:;
 case b:;
 ....
 // your code goes here
}

As said, performance wise there shouldn't be much difference, the compiler will transform this to a table lookup (or other clever things) if appropriate or completely optimize it out if val is known at compile time.

But you can have the advantage of error checking compilers, here. If you don't have a default case, most compilers will warn you if you omit one of the enumeration constants. Also I think that this is clearer, since it doesn't repeat the evaluation of val all over the place.

like image 82
Jens Gustedt Avatar answered Sep 30 '22 09:09

Jens Gustedt


other(faster) solution will be the following

bool isInenum (int val)
{
    bool retVal = false
        switch(val)

    {
        case a:
        case b:
        case c:
        case d:
            {
                retVal = true;
            }

    }
    return retVal;
}
like image 32
Adrian Herea Avatar answered Sep 30 '22 10:09

Adrian Herea