Click here to Skip to main content
15,891,473 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hey guys,

I have a small doubt regarding the switch statement.
can we use the switch statement to compare more than one character, for example :
C#
switch(I do not know which data type to use)
{
       case 'hello':
                { cout << " you typed hello ";break;} 
}
Posted
Updated 28-Sep-13 21:57pm
v2

You can't.
The expression in a switch statement must be an integer, or a type which can be unambiguously converted to an integer. A string value cannot, because it can by longer than an integer can hold.
 
Share this answer
 
Comments
pasztorpisti 29-Sep-13 5:36am    
But this is a multicharacter literal and not a string so it is basically an integer. Those are single quotes not double quotes.

EDIT: This can be done with short (max 4 byte long strings) but it would be a brutal antipattern that exploits compiler dependent behavior so the answer is indeed a big NO so +5 from me.
This is a multicharacter literal and it evaluates to a value of an integral type. The width of the integral type doesn't exceed that of the int type. I don't recommend using multicharacter literals if you are writing platform independent code. Why? http://stackoverflow.com/questions/3960954/c-multicharacter-literal[^]
You can solve the same problem in a dozen other ways without using multicharacter literals.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900