2
#include <iostream>
using namespace std;

int main(){
char i;
cin >>i;
switch (i){
 case ('e'||'i'||'o'||'u'||'a'):
     cout<<"Vowel";
     break;
 case ('+'||'-'||'/'||'*'||'%'):
     cout<<"Op";
     break;
 }
return 0;  

}

if not than how can we use comparison or logical operators in switch ? & why cant we declare and initialize variable in single case without using scope ?

Ben Voigt
  • 269,602
  • 39
  • 394
  • 697
jellly
  • 21
  • 2

6 Answers6

7

Without a break statement the previous cases "fall through" so this achieves the || you were looking for:

#include <iostream>
using namespace std;

int main(){
   char i;
   cin >>i;
   switch (i){
    case 'e':
    case 'i':
    case 'o':
    case 'u':
    case 'a':
        cout<<"Vowel";
        break;
   case '+':
   case '-':
   case '/':
   case '*':
   case '%':
        cout<<"Op";
        break;
   }
   return 0;  
}

The answer to the other part of your question is discussed in depth already on stackoverflow.

Community
  • 1
  • 1
Flexo
  • 84,884
  • 22
  • 182
  • 268
2
  1. You can use fallthrough to map multiple case values to the same action.
  2. The diagnostic message explains it -- it would be possible to jump over the initialization. But isn't it just a warning?
Ben Voigt
  • 269,602
  • 39
  • 394
  • 697
2

No, you can't; in switches you can only implicitly use the == operator and only on integral and enumeration types (§6.4.2). You should rewrite that switch as

switch (i){
 case 'e':
 case 'i':
 case 'o':
 case 'u':
 case 'a':
     cout<<"Vowel";
     break;
 case '+':
 case '-':
 case '/':
 case '*':
 case '%':
     cout<<"Op";
     break;
 }

which exploits the fall-through feature of the switch statement.

if not than how can we use comparison or logical operators in switch ?

Simply, you can't. If you want to do anything different than equality comparison with integral/enumeration types you have to write several if/else statements.

& why cant we declare and initialize variable in single case without using scope ?

It's not a problem of declaration, but of initialization; see the link in @awoodland's answer.

Matteo Italia
  • 119,648
  • 17
  • 200
  • 293
1

Format it like this:

switch (i)
{
    case 'a':
    case 'e':
    case 'i':
    case 'o':
    case 'u':
        cout << "Vowel";
        break;
}
Dave
  • 3,398
  • 19
  • 13
0

Alternative, more terse solution:

#include <cstring>

// ...

if (strchr("eioua", i)) cout << "vowel";
if (strchr("+-/*%", i)) cout << "operator";

Note that strchr considers the terminating zero part of the string, so i should not be 0.

fredoverflow
  • 246,999
  • 92
  • 370
  • 646
0

We could, except it doesn't mean what is intended (and yields the same value in both cases): you'd be performing a logical or on a bunch of non-zero integer values and the result is true in both cases.

UncleBens
  • 39,805
  • 6
  • 53
  • 90