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

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

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

    The syntax for a switch statement in C programming language is as follows:

    switch(expression) {
    
       case constant-expression  :
          statement(s);
          break; /* optional */
    
       case constant-expression  :
          statement(s);
          break; /* optional */
    
       /* you can have any number of case statements */
       default : /* Optional */
       statement(s);
    }
    
    0 讨论(0)
提交回复
热议问题