Home c++ switch case C++

switch case C++

Author

Date

Category

Why doesn’t this code work? Really, in C++ switch does not accept the string type, this is some kind of nonsense.

string text;
cin & gt; & gt; text;
switch (text) {
  case "n":
    std :: cout & lt; & lt; "Some output";
    break;
  default:
    std :: cout & lt; & lt; "Input incorrect!";
    break;
}
return 0;

Answer 1, authority 100%

string cannot be used in switch . It seems like char * is possible, but not useful. But char is fine, but in this case all lines starting with n will match the condition.

string text;
cin & gt; & gt; text;
switch (text [0]) {
  case 'n':
    std :: cout & lt; & lt; "Some output";
    break;
  default:
    std :: cout & lt; & lt; "Input incorrect!";
    break;
}
return 0;

Answer 2, authority 95%

6.4.2 Standard:

The switch statement causes control to be transferred to one of several statements, depending on the value of the condition.
The condition must be of an integer type, an enumerated type, or a class type. If a condition is of a class type, then it is contextually implicitly converted (Chapter 4) to an integer or enumerated type. If the condition type (possibly converted) is subject to integer extensions (4.5), then the value is converted to the extended type.

As you can imagine, string is not an integer, not an enumerated type and there is no implicit conversion to that 🙂

Actually switch is not syntactic sugar for if-elseif-else , it has its own specifics related to performance (“I think so “(c) Pooh :))


Answer 3, authority 100%

Yes, that’s right, in C++ the switch / case construct can only operate with integers, enumerators, or classes that can be converted to an integer type, or an enumerator:

9.4.2 The switch statement [stmt.switch]

2 The condition shall be of integral type, enumeration type, or class type. If of class type, the condition is contextually implicitly converted (Clause 7) to an integral or enumeration type. If the (possibly converted) type is subject to integral promotions (7.6), the condition is converted to the promoted type. Any statement within the switch statement can be labeled with one or more case labels as follows:

case constant-expression:

where the constant-expression shall be a converted constant expression (8.20) of the adjusted type of the switch condition.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions