switch statement - case using string/char array

Status
Not open for further replies.

jonr

Well-known member
Despite being useful, it's correctly thought that you can't do this:

char s[100];
// input s here
switch (s) {
case "test1":
...
case "test2":
...
}

But you can do this, which is almost as good. I've never had a collision with my hash function.

// JZ: hash a string to an unsigned int , perhaps AT COMPILE TIME, so it can be used in a switch statement
constexpr unsigned hash(const char *string)
{
return *string == 0 ? 17325 : *string + (*string * hash(string+1));
}

char s[100];
// input s here
switch (hash(s)) {
case hash("test1"):
...
case hash("test2"):
...
}
 
Status
Not open for further replies.
Back
Top