2

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!

John Vint
  • 39,695
  • 7
  • 78
  • 108
  • See http://stackoverflow.com/questions/252489/why-was-the-switch-statement-designed-to-need-a-break for some thought regarding this topic as applied to c. After that I believe it was a matter of following suit the whole way... – dmckee --- ex-moderator kitten Apr 23 '10 at 16:49
  • Yea it is a duplicate, I didnt search under the keyword fallthrough or else I woudlve found my answer :/ Tried to delete it but had too many answers – John Vint Apr 23 '10 at 17:30

5 Answers5

1

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.

1

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);
  }
Ron
  • 269
  • 1
  • 6
0

It's because the case labels are goto destination labels.

jonnystoten
  • 7,055
  • 2
  • 28
  • 36
0

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.

Romain Hippeau
  • 24,113
  • 5
  • 60
  • 79
0

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.

bakkal
  • 54,350
  • 12
  • 131
  • 107