+ 5

Does the switch case must only contain number? How about char or string?

24th Dec 2016, 1:52 AM
Rakki
Rakki - avatar
12 Réponses
+ 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; }
24th Dec 2016, 2:00 AM
Wen Qin
Wen Qin - avatar
+ 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.
24th Dec 2016, 2:17 AM
Hatsy Rei
Hatsy Rei - avatar
+ 6
switch case handle char and int values, but it cannot handle float/double type values.
26th Dec 2016, 3:10 PM
Saumya
Saumya - avatar
+ 3
switch can handle char, int values
27th Dec 2016, 6:17 PM
Anmol Jaiswal
Anmol Jaiswal - avatar
+ 2
it can have integer as well as char
26th Dec 2016, 10:34 AM
Himani Bhardwaj
Himani Bhardwaj - avatar
+ 1
switch cases can contain characters also..
26th Dec 2016, 10:37 AM
Laxman Madipadige
Laxman Madipadige - avatar
+ 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
26th Dec 2016, 10:39 AM
Ayush Walekar
Ayush Walekar - avatar
+ 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 ;-)
27th Dec 2016, 9:01 PM
Darius Durk
Darius Durk - avatar
0
no, it can contain characters.
26th Dec 2016, 1:29 PM
Girish Kumar
Girish Kumar - avatar
0
it can contain both int and char
26th Dec 2016, 8:53 PM
Awais Javaid
Awais Javaid - avatar
0
it contains both char & string
27th Dec 2016, 3:43 PM
Santosh Dussa
Santosh Dussa - avatar
0
you are right. it can take a character as a parameter too
27th Dec 2016, 4:17 PM
LYRICS ARE AWESOME
LYRICS ARE AWESOME - avatar