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

孤街浪徒 提交于 2020-12-27 07:12:12

问题


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);
        break;

rest of the codes are similar. And i'm getting error for this case (at>0 && at<5) :


回答1:


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;



回答2:


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.



来源:https://stackoverflow.com/questions/44627515/why-my-code-which-uses-a-logical-expression-as-a-case-label-throws-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!