问题
Two constants (1+2) share the same case statement. I don´t want to double the code.
What is the right syntax to do this?
switch (expression) {
case 0:
[self taskA];
break;
case 1:
[self taskB];
break;
case 2:
[self taskB]
break;
default:
break;
}
回答1:
Use :
switch (expression) {
case 0:
[self taskA];
break;
case 1:
case 2:
[self taskB];
break;
default:
break;
}
Edit 1:
In switch
we say a term called fall-through. Whenever control reaches to a label say case 0:
it falls till break
is found. On break
control is sent to the closing braces of switch
.
If break
is not encountered it goes to next case
as in case
then case 2
. So above case 1
and case 2
shares one break
statement.
回答2:
Multiple case labels can refer to the same statement if break or return are not used at the end of the case. If you do not use a break statement in case 1, the execution flows into case 2.
来源:https://stackoverflow.com/questions/15072171/switch-statement-syntax-for-same-action-through-different-cases