1#include <iostream>
2using namespace std;
3
4int main() {
5 // variable declaration
6 int input;
7 switch(input){
8 case 1: case 2: case 3: case 4:
9 //executes if input is 1, 2, 3, or 4
10 break;
11 case 5: case 6: case 7:
12 //executes if input is 5, 6, or 7
13 break;
14 default:
15 //executes if input isn't any of the cases
16 }
17 return 0;
18}
1switch(expression) {
2 case x:
3 // code block
4 break;
5 case y:
6 // code block
7 break;
8 default:
9 // code block
10}
1switch (n)
2{
3 case 1: // code to be executed if n = 1;
4 break;
5 case 2: // code to be executed if n = 2;
6 break;
7 default: // code to be executed if n doesn't match any cases
8}
1switch(a) {
2 case -1:
3 std::cout << "a == -1" << std::endl;
4 break;
5
6 case 0:
7 std::cout << "a == 0" << std::endl;
8 break;
9
10 default:
11 std::cout << "a is something else" << std::endl;
12}
1switch(expression) {
2 case 1:
3 //equivalent to if(expression == 1){//do someting...}
4 //do something...
5 break;
6 //if case 1 is true the rest of the statments arn't
7 //evaluated because of the break
8 case 45:
9 //equivalent to else if(expression == 45){//do someting...}
10 //do something...
11 break;
12
13 // you can have any number of case statements and default has to be last
14 default :
15 // equivalent to else{//do someting...}
16 //do something...
17}
18
19switch(expression) {
20 case 1:
21 //equivalent to if(expression == 1){//do someting...}
22 //do something...
23 case 45:
24 //equivalent to if(expression == 45){//do someting...}
25 //do something...
26 default :
27 //always runs if there are no breaks in any of the cases
28 //do something...
29}
30
31//modification of answer by Homeless Hoopoe
1// Transfers control to one of the several statements, depending on the
2//value of a condition.
3switch (variable or an integer expression) {
4 case constant: {
5 //C++ code
6 break;
7 }
8 case constant: {
9 //C++ code
10 break;
11 }
12 default: {
13 //C++ code
14 break;
15 }
16}