12

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.

1
  • x = *++s &~ *++m; == x = (*(++s)) & (~(*(++m)));..default: is like any other case if you don't write as last you need to add break; statement for same reason we other case Commented Aug 27, 2013 at 16:17

1 Answer 1

16

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.

3
  • 1
    Not sure if I quite get the reasoning for the second part of the answer. The assumption being that it is more dangerous to fall through to default than any other case?
    – Ziffusion
    Commented Aug 27, 2013 at 16:06
  • 3
    @Ziffusion the reasoning is as follows: People believe that default should only be hit if there is no matching value. Putting it at the top makes visually easier to validate this is indeed the case. It also makes future additions which do fall through and violate the assumption about default much more visible. Note I'm not saying I agree with it, this is simply the logic others have presented to me in the past
    – JaredPar
    Commented Aug 27, 2013 at 16:08
  • 1
    Thank you so much, @JaredPar, I thought that swith-case works like if('a'){/*something*/}else if('b'){/*something else*/} else{/*quite another*/}, and default clause is something like the last else without if(...). I think this is an important aspect of the C language, so thank you again.
    – Netherwire
    Commented Aug 27, 2013 at 16:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.