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?
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?
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 case
s, and after all it isn't hard to put the break
s 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.");
}