Control Flow
Switch Statement
A switch statement compares one value against several case labels.
Switch Statement
switch_statement.cpp
#include <iostream>
#include <string>
int main() {
int option = ;
std::string action = "";
switch (option) {
case 1:
action = "create";
break;
case 2:
action = "update";
break;
case 3:
action = "delete";
break;
default:
action = "help";
break;
}
std::cout << "option=" << option << std::endl;
std::cout << "action=" << action << std::endl;
return 0;
}
#include <iostream>
#include <string>
int main() {
int option = ;
std::string action = "";
switch (option) {
case 1:
action = "create";
break;
case 2:
action = "update";
break;
case 3:
action = "delete";
break;
default:
action = "help";
break;
}
std::cout << "option=" << option << std::endl;
std::cout << "action=" << action << std::endl;
return 0;
}
#include <iostream>
#include <string>
int main() {
int option = ;
std::string action = "";
switch (option) {
case 1:
action = "create";
break;
case 2:
action = "update";
break;
case 3:
action = "delete";
break;
default:
action = "help";
break;
}
std::cout << "option=" << option << std::endl;
std::cout << "action=" << action << std::endl;
return 0;
}
#include <iostream>
#include <string>
int main() {
int option = ;
std::string action = "";
switch (option) {
case 1:
action = "create";
break;
case 2:
action = "update";
break;
case 3:
action = "delete";
break;
default:
action = "help";
break;
}
std::cout << "option=" << option << std::endl;
std::cout << "action=" << action << std::endl;
return 0;
}
switch
Use `switch` when one value chooses among several named cases.