views:

159

answers:

6

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!

A: 

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

applechewer
+4  A: 

See the answers to this existing question.

Lord Torgamus
Thanks I was looking for an exisitng question
John V.
Just use a comment for this kind of thing.
dmckee
@dmckee, I tell people that sometimes too, but in this case I think it qualifies as an answer since those answers answer this.
Lord Torgamus
Yes, and also vote to close. This is not an offense to the poster, it just helps keep the site clean.
danben
Yes, this was originally intended to be a combination "here's an answer," "close as dupe" and "quick-and-dirty answer while I find more information to add." But since it's been 20 minutes I guess it won't be closed. I remember seeing a more exact dupe somewhere else but I can't find it; I guess it might not have been on SO.
Lord Torgamus
A: 

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.

doublep
A: 

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
+1  A: 

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
A: 

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