Switch statement: must default be the last case?

后端 未结 10 2176
面向向阳花
面向向阳花 2020-11-27 02:36

Consider the following switch statement:

switch( value )
{
  case 1:
    return 1;
  default:
    value++;
    // fall-through
  case 2:
    ret         


        
10条回答
  •  情书的邮戳
    2020-11-27 03:16

    The default condition can be anyplace within the switch that a case clause can exist. It is not required to be the last clause. I have seen code that put the default as the first clause. The case 2: gets executed normally, even though the default clause is above it.

    As a test, I put the sample code in a function, called test(int value){} and ran:

      printf("0=%d\n", test(0));
      printf("1=%d\n", test(1));
      printf("2=%d\n", test(2));
      printf("3=%d\n", test(3));
      printf("4=%d\n", test(4));
    

    The output is:

    0=2
    1=1
    2=4
    3=8
    4=10
    

提交回复
热议问题