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.
The default case is only jumped to from the
switchstatement if no other cases match. After one of them has matched, the code executes as if none of thecasestatements existed, unless it hits abreak. So thedefaultcase 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:
But this is talking about how the
switchstatement branches. Fallthrough behavior is on the next page:which doesn't depend on whether or not there's a
defaultcase.The C standard is clearer:
Once control jumps, the
caseanddefaultlabels don't matter anymore.