How add "or" in switch statements?

Ivan Prodanov picture Ivan Prodanov · May 11, 2009 · Viewed 120.4k times · Source

This is what I want to do:

switch(myvar)
{
    case: 2 or 5:
    ...
    break;

    case: 7 or 12:
    ...
    break;
    ...
}

I tried with "case: 2 || 5" ,but it didn't work.

The purpose is to not write same code for different values.

Answer

Jose Basilio picture Jose Basilio · May 11, 2009

By stacking each switch case, you achieve the OR condition.

switch(myvar)
{
    case 2:
    case 5:
    ...
    break;

    case 7:
    case 12:
    ...
    break;
    ...
}