Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++ switch case with string [duplicate]

Tags:

c++

Possible Duplicate:
C/C++: switch for non-integers

Hi, I need to use a string in switch case. My solution so far was to calculate the hash of the string with my hash function. Problem is I have to manually pre-calculate all my hash values for strings. Is there a better approach?

h=_myhash (mystring); switch (h) { case 66452:    ....... case 1342537:    ........ } 
like image 784
Luke Avatar asked Dec 18 '10 23:12

Luke


People also ask

Can Switch case have duplicates?

If two cases in a 'switch' statement are identical, the second case will never be executed. This most likely indicates a copy-paste error where the first case was copied and then not properly adjusted.

Can I use string in switch case in C?

No you can't.

Can switch statements use doubles in C?

The value of the expressions in a switch-case statement must be an ordinal type i.e. integer, char, short, long, etc. Float and double are not allowed. The case statements and the default statement can occur in any order in the switch statement.

Can you use Switch case with strings?

Yes, we can use a switch statement with Strings in Java.


1 Answers

Just use a if() { } else if () { } chain. Using a hash value is going to be a maintenance nightmare. switch is intended to be a low-level statement which would not be appropriate for string comparisons.

like image 192
tenfour Avatar answered Sep 22 '22 14:09

tenfour