Why the switch statement cannot be applied on strings?

前端 未结 20 2565
离开以前
离开以前 2020-11-22 03:58

Compiling the following code and got the error of type illegal.

int main()
{
    // Compilation error - switch expression of type illegal
    sw         


        
相关标签:
20条回答
  • 2020-11-22 04:44

    C++

    constexpr hash function:

    constexpr unsigned int hash(const char *s, int off = 0) {                        
        return !s[off] ? 5381 : (hash(s, off+1)*33) ^ s[off];                           
    }                                                                                
    
    switch( hash(str) ){
    case hash("one") : // do something
    case hash("two") : // do something
    }
    
    0 讨论(0)
  • 2020-11-22 04:44

    in many cases you can avid extra work by pulling the first char from the string and switching on that. may end up having to do a nested switch on charat(1) if your cases start with the same value. anyone reading your code would appreciate a hint though because most would prob just if-else-if

    0 讨论(0)
提交回复
热议问题