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?
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.
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.
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.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With