The typical syntax for a switch-statement is:
switch(expression) {
case one:
// do something...
break;
case two:
// do something else...
break;
case three:
case four:
// do something special
break;
default:
// if nothing matches...
break;
}
This syntax looks very Python-like (especially the colons and the way people indent it), contrary to the general syntax of languages such as JavaScript, Java, or C, where curly braces are used for most statements. Is there any specific reason?
I would expect that it should look more like:
switch(expression) {
case (one) {
// do something...
break;
} case (two) {
// do something else...
break;
} case (three) case (four) {
// do something special
break;
} default {
// if nothing matches...
break;
}
}
I think the example I just provided looks like an if-else if-else statement, but shouldn't a switch statement match the syntax style?
case
as a label for agoto
. But there is nogoto
, instead theswitch
is jumping to the label. – Enureswitch (expression) { case one: { // do something } break; }
– Highsmithswitch
statement found matching case, every code below that case executed until meetbreak
. Syntax what you suggest seems run only matching case. – Salicylatebreak;
). The C# people thought so, so they only let you do it if you explicitly usegoto nextLabel;
. – Aufmannswitch
statement if you're creative. Check out Duff's device. – Jooswitch
statements in particular have a rather weird and brittle syntax. – Recoil