can we write this in C++ switch?
#include <iostream>
using namespace std;
int main(){
ch开发者_运维技巧ar 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 ?
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.
- You can use fallthrough to map multiple case values to the same action.
- The diagnostic message explains it -- it would be possible to jump over the initialization. But isn't it just a warning?
No, you can't; in switch
es 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.
Format it like this:
switch (i)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
cout << "Vowel";
break;
}
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.
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.
精彩评论