Default clause before sections in switch statement

This is detected 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; } 

This may not be a good example, but I canโ€™t understand how it works and what prompted Linus to put the default section before the switch statement.

+8
c switch-statement
source share
1 answer

The order of case labels in the switch block in the code has nothing to do with which one is executed. The default label is executed if the case does not match or it passes through the case above it. Having it first in the code base does not change this.

The only advantage of having default in the first place is that it is impossible for a case to accidentally or intentionally fail over it to default . This means that default will be executed if and only if the value does not match the case in the switch block.

To be extremely pedantic, you can still click on the default label with explicit goto . This is pretty rare.

+10
source share

All Articles