cswitch-statementfall-through

Switch Case Fall Through Scenario


So I came upon a competitive question (asking the output) as follows:

#include <stdio.h>
int main()
{
    int i = 0;
    for(i = 0; i < 20; i++)
    {
        switch(i)
        {
            case 0: i+=5;
            case 1: i+=2;
            case 5: i+=5;
            default: i+= 4;
            break;
        }
        printf("%d ", i);
    }
    return 0;
}

The output is 16, 21. While I know how switch case works I am unable to explain myself how this fall through works. Why is the default getting added? Doesn't K&R C book say that the default only executes if none of cases match?
Thanks.


Solution

  • The default case is only jumped to from the switch statement if no other cases match. After one of them has matched, the code executes as if none of the case statements existed, unless it hits a break. So the default case isn't "jumped over" the way you seem to expect.

    K & R is a little bit unclear about this, the line you're referring to seems to be:

    If a case matches the expression value, execution starts at that case. All case expressions must be different. The case labeled default is executed if none of the other cases are satisfied

    But this is talking about how the switch statement branches. Fallthrough behavior is on the next page:

    Because cases serve just as labels, after the code for one case is done, execution falls through to the next unless you take explicit action to escape.

    which doesn't depend on whether or not there's a default case.

    The C standard is clearer:

    A switch statement causes control to jump to, into, or past the statement that is the switch body , depending on the value of a controlling expression ... If a converted value matches that of the promoted controlling expression, control jumps to the statement following the matched case label. Otherwise, if there is a default label, control jumps to the labeled statement.

    Once control jumps, the case and default labels don't matter anymore.