Problems with case 'p' || 'P': syntax within a switch statement in C++

匆匆过客 提交于 2020-01-11 05:51:46

问题


I've used the switch statement the following way:

   switch (ch){
   case 'P' || 'p': 
        goto balance;
        break;

   case 'r' || 'R':
        goto menu;
        break;

   default:
           cout<<"\t\tInvalid Choice!!"<<endl;
           system ("\t\tpause");
           system ("cls");
           goto menu;
           break;
           }

But it seems there's something wrong with the following syntax:

case 'r' || 'R'

Compiler complains about "duplicate case value". What's wrong with my code?


回答1:


Change it to

case 'P':
case 'p': 
    goto balance;
    break;

Using goto is usually not a good idea.


In your original code, case 'P' || 'p': is equivalent to case 1 as the result of || is 0 if both operand are zero, or 1 otherwise. So in the two case statement, both 'p' || 'P' and 'r' || 'R' evaluated as 1, that's why you got the warning about duplicate case value.




回答2:


case 'P' || 'p': 
    ...

was meant to be:

case 'P':
case 'p':
    ...

Note that there is another (in this case more reasonable) approach you could use:

switch ( std::tolower(ch) ) {
case 'p': 
     ...
     break;
case 'r':
     ...
     break; 

default:
     ...
}

you'll just have to #include <cctype>




回答3:


|| is a binary operator; 'P' || 'p' evaluates to true, because the left-hand operand of || is non-zero. Same thing for 'R' || 'r'. So both case statements are case true:, and that's what the compiler is complaining about. Separate the values:

case 'P':
case 'p':
    menu(); // function call recommended instead of `goto`
    break;


来源:https://stackoverflow.com/questions/19308586/problems-with-case-p-p-syntax-within-a-switch-statement-in-c

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