3

Possible Duplicate:
Why was the switch statement designed to need a break?

The interesting phenomenon of most popular language [c, c++, java] is that switch by default is fall-through.

I am curious about reason, does someone know this story?

Community
  • 1
  • 1
Chang
  • 3,953
  • 2
  • 30
  • 43
  • I don't know the history, but if it weren't, there would be not difference between a switch block and an if-elseif block. – Augusto Sep 11 '12 at 07:53
  • In future, please use the search function before asking a question that has already been asked many times before. – verdesmarald Sep 11 '12 at 07:55
  • 1
    C# is a rather strange case - there is no possibility of fall-through, but you still need to specify a 'break' (or 'return', etc.). So you need to explicitly state that there's no fall-through even though you can't have fall-through. – Dave Doknjas Sep 11 '12 at 14:20

1 Answers1

1

In C the reason for this was the intention to make switch easily-opimizable into a jump table, Basically, based on the expression, the app will calculate the jump distance, jump to a certain point, and continue executing from that point.

I, however, think that this behavior is useful sometimes, because it helps to avoid code repetition in multiply cases, and after all it isn't hard to put the breaks when you need it.

Wiki has a decent example to illustrate how the fall-down can be utilized:

switch (n) {
  case 0:
    printf("You typed zero.");
    break;
  case 4:
    printf("n is an even number.");
  case 1:
  case 9:
    printf("n is a perfect square.");
    break;  
  case 2:
    printf("n is an even number.");
  case 3:
  case 5:
  case 7:
    printf("n is a prime number.");
    break;
  case 6:
  case 8:
    printf("n is an even number.");
    break;
  default:
    printf("Only single-digit numbers are allowed.");
}
SingerOfTheFall
  • 29,228
  • 8
  • 68
  • 105
  • An alternative design *could* have made break the default, and required an explicit fall-through. That would have save a lot of people from forgetting the break. – Bo Persson Sep 11 '12 at 08:01
  • @Bo, yes, but if they used, say `continue` to force the fall-through, it would have been a little ambiguous. Like "where will it continue? Will it continue going through the cases, or will it continue the execution after the `switch`?" Though I agree that the way it works now isn't very intuitive either. – SingerOfTheFall Sep 11 '12 at 08:05