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

前端 未结 2 773
温柔的废话
温柔的废话 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 10:54

    The case value in a switch statement must be a compile time constant (such as a literal, or a static const, or a #define to one of those). For what you are trying to do, you need an else if chain:

    if (0 < at && at < 5) {
        printf("Average Time Taken (Hrs)\n%d.0",at);
        printf("Your Salary is Rs.%d",pj*1500 + 5000);
    } else if (5 <= at && at < 10) {
        // Your code here
    

    Note that I have reversed the arguments to the first comparison (and the direction). If you have multiple comparisons of the same variable, I find it much easier to read if they are all in the same direction.

提交回复
热议问题