Why do switch statements continue after case [duplicate]
After evaluating a case in a switch statement in Java (and I am sure other languages) the following case's are also evaluated unless a control statement like break, or return is used.
I understand this is probably an implementation detail, but what is/are the reasons for having this functionality happen?
Thanks!
Because it is useful to "fallthrough" from one case to another. If you don't need this (as is often the case), a simple break
will prevent this. On the other hand, if case didn't fallthrough by default, there wouldn't be any easy way to do that.
It saves me a lot of duplicated code when the hardware changes.
void measureCPD (void) {
char setting;
switch (DrawerType) {
case 1:
setting = SV1 | SV7;
break;
case 0:
case 2:
setting = SV1;
break;
case 5:
PORTA |= SVx;
case 3:
case 4:
setting = SV1 | SV7;
break;
default: // Illegal drawer type
setting = SV1;
}
SetValves (setting);
}
It's because the case labels are goto
destination labels.
There are times where you might want to have multiple case statement execute the same code. So you would fall through and do the break at the end.
I tend to think of it in analogy to assembly programming, the case
's are labels where you jump into, and it runs through the ones below it (program flows from up to down), so you will need a jump (break;
) to get out.
精彩评论