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

后端 未结 8 647
一向
一向 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: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.

提交回复
热议问题