Multiple cases in switch statement

theo picture theo · Sep 16, 2008 · Viewed 908.9k times · Source

Is there a way to fall through multiple case statements without stating case value: repeatedly?

I know this works:

switch (value)
{
   case 1:
   case 2:
   case 3:
      // Do some stuff
      break;
   case 4:
   case 5:
   case 6:
      // Do some different stuff
      break;
   default:
       // Default stuff
      break;
}

but I'd like to do something like this:

switch (value)
{
   case 1,2,3:
      // Do something
      break;
   case 4,5,6:
      // Do something
      break;
   default:
      // Do the Default
      break;
}

Is this syntax I'm thinking of from a different language, or am I missing something?

Answer

Carlos Quintanilla picture Carlos Quintanilla · Aug 1, 2010

I guess this has been already answered. However, I think that you can still mix both options in a syntactically better way by doing:

switch (value)
{
    case 1: case 2: case 3:          
        // Do Something
        break;
    case 4: case 5: case 6: 
        // Do Something
        break;
    default:
        // Do Something
        break;
}