Multiple cases in switch statement


Question

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?

1
536
11/30/2017 9:37:04 AM

Accepted Answer

There is no syntax in C++ nor C# for the second method you mentioned.

There's nothing wrong with your first method. If however you have very big ranges, just use a series of if statements.

293
9/16/2008 2:30:06 AM

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;
}

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon