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.
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.
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).
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.
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;
}
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