What if I don't write default in switch case?

后端 未结 8 616
一向
一向 2020-12-13 17:09
int a = 10;
switch(a){
case 0:
    printf(\"case 0\");
    break;
case 1:
    printf(\"case 1\");
    break;
}

Is the above code valid?

If

相关标签:
8条回答
  • 2020-12-13 17:36

    yes the above code is valid,

    if the switch condition doesn't match any condition of the case and a default is not present the program execution go ahead exiting from the switch without doing anything.

    0 讨论(0)
  • 2020-12-13 17:38

    It is perfectly legal code. If a is neither 0 or 1, then the switch block will be entirely skipped.

    0 讨论(0)
  • 2020-12-13 17:41

    It's valid not to have a default case.

    However, even if you are sure that you will not have any value rather than 1 and 0, it's a good practice to have a default case, to catch any other value (although it is theoretically impossible, it may appear in some circumstances, like buffer overflow) and print an error.

    0 讨论(0)
  • 2020-12-13 17:41

    Default is not mandatory but always good to have it. The code is ideally but our life is not, no harm to put a protection there. It will also help you debugging if any unexpected thing happens.

    0 讨论(0)
  • The code is valid. If there is no default: label and none of the case labels match the "switched" value, then none of the controlled compound statement will be executed. Execution will continue from the end of the switch statement.

    ISO/IEC 9899:1999, section 6.8.4.2:

    [...] If no converted case constant expression matches and there is no default label, no part of the switch body is executed.

    0 讨论(0)
  • 2020-12-13 17:44

    It's same like no if condition is matched and else is not provided.

    default is not an mandatory in switch case. If no cases are matched and default is not provided, just nothing will be executed.

    0 讨论(0)
提交回复
热议问题