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

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

    As others have pointed out it is perfectly valid code. However, from a coding style perspective I prefer adding an empty default statement with a comment to make clear that I didn't unintentionally forget about it.

    int a=10;
    switch(a)
    {
    case 0: printf("case 0");
             break;
    case 1: printf("case 1");
             break;
    default: // do nothing;
             break;
    }
    

    The code generated with / without the default should be identical.

提交回复
热议问题