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