Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 317
student13 Avatar asked Nov 29 '22 12:11

student13


1 Answers

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.

like image 166
Yu Hao Avatar answered Dec 09 '22 08:12

Yu Hao