Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I concisely compare a single variable to many different values?

I know you can write a statement like:

if (num1 != a && num1 != b && num1 != c ..........&& num1 != z)
   (do something);

But is there an easier way to compare the num1 variable to 26 other variables? Kinda like:

if (num1 != a,b,c,d,e,f,g.......)
   (do something);
like image 477
Crash_Override Avatar asked Mar 21 '11 07:03

Crash_Override


3 Answers

If a..g are contiguous constant/enum values then just use a range check.

if (num >= a && num <= g)
{
    do_something();
}
else
{
    do_something_else();
}

If they are non-contiguous but constant then maybe use a switch statement.

switch (num)
{
    case a:
    case b:
    case c:
    case d:
    case e:
    case f:
    case g:
        do_something();
        break;

    default:
        do_something_else();
        break;
}

otherwise if they are just arbitrary variables or expressions then you may have just have to do it with multiple tests.

like image 75
Paul R Avatar answered Nov 02 '22 23:11

Paul R


You can put a, ... ,z into a std::set and then use the find method of that set to check if num1 is in there. This has logarithmic complexity, but does not allow for short-circuiting.

like image 20
Björn Pollex Avatar answered Nov 02 '22 23:11

Björn Pollex


First of all, a good code design should not include so many sequence of conditions.

If your case is exactly the way it is, that is trying to see if a number exists in a list, where the list is actually a collection of variables. You could simply enter those numbers into the list( vector ) and perform find operation.

like image 45
Shamim Hafiz - MSFT Avatar answered Nov 02 '22 23:11

Shamim Hafiz - MSFT