jellly
jellly

Reputation: 21

can we write this in C++ switch?

#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 ?

Upvotes: 2

Views: 1112

Answers (6)

UncleBens
UncleBens

Reputation: 41351

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.

Upvotes: 0

fredoverflow
fredoverflow

Reputation: 263260

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.

Upvotes: 0

Matteo Italia
Matteo Italia

Reputation: 126877

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.

Upvotes: 2

Ben Voigt
Ben Voigt

Reputation: 283773

  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?

Upvotes: 2

Dave
Dave

Reputation: 3448

Format it like this:

switch (i)
{
    case 'a':
    case 'e':
    case 'i':
    case 'o':
    case 'u':
        cout << "Vowel";
        break;
}

Upvotes: 1

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.

Upvotes: 7

Related Questions