Why my code which uses a logical expression as a case label throws error?

前端 未结 2 729
温柔的废话
温柔的废话 2021-01-29 10:43
switch(at){
case (at>0 && at<5) :
        printf(\"Average Time Taken (Hrs)\\n%d.0\",at);
        printf(\"Your Salary is Rs.%d\",pj*1500 + 5000);
                 


        
2条回答
  •  太阳男子
    2021-01-29 11:14

    I'm afraid this is not possible. Quoting C11, chapter §6.8.4.2

    The expression of each case label shall be an integer constant expression and no two of the case constant expressions in the same switch statement shall have the same value after conversion. [....]

    so the case label expression cannot be a runtime-generated value dependent.

    You can, use a fall-through syntax to achieve what you want, something like

    switch(at){
    case 1:
    case 2:
    case 3:
    case 4:
            printf("Average Time Taken (Hrs)\n%d.0",at);
            printf("Your Salary is Rs.%d",pj*1500 + 5000);
            break;
    
      //some other case
    

    Otherwise, if you're ok with using gcc extension, you can use case-range syntax, something like

    switch(at){
    case 1 ... 4:
            printf("Average Time Taken (Hrs)\n%d.0",at);
            printf("Your Salary is Rs.%d",pj*1500 + 5000);
            break;
    

提交回复
热议问题