Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default clause before case sections in the switch statement

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.

like image 485
Netherwire Avatar asked Aug 27 '13 15:08

Netherwire


People also ask

Can default come before case in switch?

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.

What is default in a switch case?

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.

Does a switch statement need a default clause?

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.

What does the default option do in a switch statement?

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.


1 Answers

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.

like image 98
JaredPar Avatar answered Oct 04 '22 06:10

JaredPar