switch case

can we use string declaration in switch case

example:

switch(string)
case "string":
Last edited on
nope
why we cannot use string in switch case?
can someone explain it to me!!
no, you can compare a single character though...
I normally use if statement to compare string like:
1
2
3
4
5
6
7
8
int main()
{
  string a="hello";
  string b;
  cin>>b;
  if(a==b)
    cout<<"the strings are the same";
}

you could use similar logic to use else if ladder instead of switch.
there might be a better method, i'm kinda new to c++.
Last edited on
From the creator of the C++:

Here are some technical details abom switch·statements:
1. The value on which we switch must be of an integer, char, or enumeration type. In particular, you cannot switch on a string.
2. The values in the case labels must be constant expressions. In particular, you cannot use a variable in a case label.
3. You cannot use the same value for two case labels.
4. You can use several case labels for a single case.
5. Don't forget to end each case with a break. Unfortunately, the compiler won't warn you if you forget.


In other words, the use of strings in switch cases, is not part of the ISO C++ standard.
Last edited on
why we cannot use string in switch case?

The switch statement lets you implement a jump table in a high level language. It exists because jump tables are absurdly fast. Basically, you can use the switch value as the index into a table to find the appropriate case statement. Since you can't do that with a non-integral type, the language requires that you use a series of if/then/else statements instead, or somehow map the strings to integral values and switch off of those.
Topic archived. No new replies allowed.