Found this in linux/kernel/signal.c
switch (_NSIG_WORDS) {
default:
for (i = 1; i < _NSIG_WORDS; ++i) {
x = *++s &~ *++m;
if (!x)
continue;
sig = ffz(~x) + i*_NSIG_BPW + 1;
break;
}
break;
case 2:
x = s[1] &~ m[1];
if (!x)
break;
sig = ffz(~x) + _NSIG_BPW + 1;
break;
case 1:
/* Nothing to do */
break;
}
Maybe this is not quite good example, but I can't understand how it works and what prompted Linus to put default-section at front of the switch statement.
There can be at most one default statement. The default statement doesn't have to come at the end. It may appear anywhere in the body of the switch statement. A case or default label can only appear inside a switch statement.
A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.
No it is not necessary of default case in a switch statement and there is no rule of keeping default case at the end of all cases it can be placed at the starting andd middle of all other cases.
Hint 1. Adding a default option makes sure that in case your variable doesn't match any of the options, the default will be used.
The order of case
labels within a switch
block in the code has nothing to do with which one is executed. The default
label is executed if no case
matches or it falls through from a case
above it. Having it first in the code base doesn't change this.
The one advantage to having default
be first is that it's impossible for a case
above it to accidentally or intentionally fall through to default
. This means default
will run if, and only if, the value matches no case
statements in the switch
block.
To be extremely pedantic you could still hit the default
label with an explicit goto
. That is pretty rare though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With