Reputation: 43
Yesterday I saw the below code. As you can see it hasn't got any break
I predicted that it would print "354" because I thought the default
part would be finally evaluated (after checking all the cases.)
But that isn't practically correct as it printed "345". Can somebody explain the reason?
int main ()
{
int a = 2;
switch (2*a-1)
{
case 1: printf ("1");
case 2: printf("2");
case 3: printf("3");
default: printf("4");
case 5: printf("5");
}
}
Upvotes: 0
Views: 44
Reputation: 182829
Since 2*a-1
is 3, the code jumped to the case 3
label and kept running from there. The other labels were ignored because no code ever jumped to them. The default
label is only jumped to if the value in the switch
doesn't match any of the case
labels.
Upvotes: 3