开发者

Why do switch statements continue after case [duplicate]

This question already has answers here: 开发者_Python百科 Switch statement fall-through...should it be allowed? [closed] (12 answers) Closed 9 years ago.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜