+ 5
Does the switch case must only contain number? How about char or string?
12 ответов
+ 12
They can contain char or strings, example :
char z = 'D';
switch(z) {
case 'A' :
cout << "A" << endl;
break;
case 'B' :
cout << "B" << endl;
case 'C' :
cout << "C" << endl;
break;
case 'D' :
cout << "D" << endl;
break;
default :
cout << "???" << endl;
}
+ 11
Erm, while the example K2 provided is valid, I don't think strings can be used as case for switch statements. I've tested it on both Code Playground and offline IDEs. Works with char and int variables though, but certainly not strings.
+ 6
switch case handle char and int values, but it cannot handle float/double type values.
+ 3
switch can handle char, int values
+ 2
it can have integer as well as char
+ 1
switch cases can contain characters also..
+ 1
char n int only
switch(1+2) //case 3 will be executed
or
int b=1; char a='A';
switch(a+b) //case 'B' ..will be executed
or
switch(a,b) //rightmost value will be alloted
or
it also works with functions with return type of int or char
+ 1
Hmm if we are correct at all switch just handles with integers. It works with chars as well but that is just because every char can be interpreted as a specific int and that is what switch does with chars.
internal there must be sth like this
case int(x): for chars... you can test it... just by
console.writeline(int("g"));
Note the number you get and then check the "g" in a switch against a case with the number you got. it should work if im not completely wrong.
with a little trick you can handle strings as well.
enum colors = { red, green, blue };
colors x = colors.green;
switch(x) {
case colors.red:
break;
case colors.green:
break;
etc...
}
at least its again integers... you can just write case 0: case 1:... itll work. just the readability of your code will be a little better.
hope this will help ;-)
0
no, it can contain characters.
0
it can contain both int and char
0
it contains both char & string
0
you are right. it can take a character as a parameter too