简体   繁体   中英

When we don't use 'break' statement in switch statements,why is 'deafult' evaluated before other cases that is below 'default'?

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");
        }
    }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM