0

I can't make it, the compiler doesn't like me. it says " This constant expression has type const char instead of the required int type"

My code

#include<string>         
#include<iostream>                         

using namespace std;

void StupidSwitch(string str) {

    switch (str)
    {
    case "whhy":
    // DoSomethingElse();
    break;
    case "not":
    // DoSomethingElse();
    break:
    case "working":
    // DoSomethingElse();
    break;

    default:
    // DoSomethingElse();
    break;
    }
}

I already tried to change the passing from void StupidSwitch(string str) to void StupidSwitch(const char str) but the compiler says the same thing again " This constant expression has type const char instead of the required int type".

  • Does this answer your question? [Why the switch statement cannot be applied on strings?](https://stackoverflow.com/questions/650162/why-the-switch-statement-cannot-be-applied-on-strings) – Passerby Nov 03 '21 at 07:32
  • 1
    You can't switch on strings in C++, only on integral types. Any decent introduction to `switch` should mention this. – molbdnilo Nov 03 '21 at 07:33
  • @molbdnilo Thanks for your message does this mean I have to do millions of if and else if in c++. that would make no sense is there another option? – devnewcoomer Nov 03 '21 at 07:36
  • 1
    Yes, there are other options. For example, you can store your strings in a `std::unordered_map` or similar associative container and take appropriate action. That can even map a string to a function pointer or lambda to do the appropriate thing. Then it's just a matter of searching the map and doing the thing. – paddy Nov 03 '21 at 07:39
  • For more special-case applications, let's say you don't want to copy all these strings into memory (they are already stored once in the program after all), and you also don't want to build an index. Well, you could define a single static table containing pairs of string literals and associated function pointer to handle that string. Then before first-use you sort that table by the strings. Now you can do any string lookup in O(logN) time by binary-searching with `std::lower_bound`, and you didn't have to fill up the heap by building an index -- the definition table _is_ the index. – paddy Nov 03 '21 at 07:47
  • @paddy thank you, that sounds good i will give it a try – devnewcoomer Nov 03 '21 at 07:51

0 Answers0