Converting the GNU case range extension to standard C

前端 未结 4 1456
猫巷女王i
猫巷女王i 2021-01-12 08:09

The GNU case range extension allows case ranges in switch statements:

switch (value) {
    case 1 ... 8:
        printf(\"Hello, 1 to 8\\n\");
        break;         


        
4条回答
  •  天命终不由人
    2021-01-12 08:30

    switch(value) 
    {
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
        case 6:
        case 7:
        case 8:
            printf("Hello, 1 to 8\n"); 
            break;     
        default:         
            printf("Hello, default\n");         
            break; 
    } 
    

    EDIT: To answer the comment.
    If you have too many cases, then You might want to consider replacing the switch-case with if-else constructs. It can be much cleaner, concise & readable.

    if (value >=1 && value <= 8) 
    {    
        printf("Hello, 1 to 8\n"); 
    } 
    else 
    {   
        printf("Hello, default\n"); 
    }  
    

提交回复
热议问题