Question 3
Back to Exercise
The program below does not compile. Which statement correctly describes the problem?
#include <iostream>
#include <string>
int main() {
std::string cmd = "start";
switch (cmd) {
case "start": std::cout << "starting\n"; break;
case "stop": std::cout << "stopping\n"; break;
}
return 0;
}
- A The cases need braces
- B switch works only with integral and enum values; use if / else if or a map from string to action Correct
- C break is not allowed
- D cmd must be const
Correct Answer: Option B
Case labels must be integer constant expressions. A std::map<std::string, std::function<void()>> is a clean replacement for many commands.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!