mercredi 29 juin 2016

C - Most succinct way to check if a variable is *none* of many options?

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:

Aucun commentaire:

Enregistrer un commentaire