Background:
Often, we developers must check if a single variable is at least one of many options. For example,
if ( (data == 125) || (data == 500) || (data == 750) )
{
/* ... do stuff ...*/
}
The suggestion here (albeit written in C#), provides an elegant solution to use a switch
statement like so,
switch ( data )
{
case 125:
case 500:
case 750:
/* ... do stuff ...*/
break;
default:
break;
}
This works well for "or" conditionals, but is ugly for negated "or" conditionals like the following,
if ( !( (data == 125) || (data == 500) || (data == 750) ) )
{
/* ... do stuff ...*/
}
which could be written as
switch ( data )
{
case 125:
case 500:
case 750:
break;
default:
/* ... do stuff ...*/
break;
}
and seems a bit hackish.
Question:
Is there a more succinct way to check if a single variable is none of many options, like the negated "or" conditional above?
References:
- C++ Most efficient way to compare a variable to multiple values?
- C# Comparing a variable to multiple values
Aucun commentaire:
Enregistrer un commentaire