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
  • 277,958
  • 43
  • 419
  • 720
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
  • 87,323
  • 22
  • 191
  • 272
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
  • 277,958
  • 43
  • 419
  • 720
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
  • 123,740
  • 17
  • 206
  • 299
1

Format it like this:

switch (i)
{
    case 'a':
    case 'e':
    case 'i':
    case 'o':
    case 'u':
        cout << "Vowel";
        break;
}
Dave
  • 3,438
  • 20
  • 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
  • 256,549
  • 94
  • 388
  • 662
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
  • 40,819
  • 6
  • 57
  • 90