Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple cases in switch statement

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?

like image 919
theo Avatar asked Sep 16 '08 01:09

theo


People also ask

Can you have multiple cases in a switch statement?

As per the above syntax, switch statement contains an expression or literal value. An expression will return a value when evaluated. The switch can includes multiple cases where each case represents a particular value.

How many cases can a switch statement have?

Microsoft C doesn't limit the number of case values in a switch statement. The number is limited only by the available memory. ANSI C requires at least 257 case labels be allowed in a switch statement.

How do you combine switch cases?

Whenever you want to combine multiple cases you just need to write a case with case label and colons(:). You can't provide the break statement in between of combined cases.


1 Answers

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; } 
like image 111
Carlos Quintanilla Avatar answered Sep 20 '22 13:09

Carlos Quintanilla