switch example in c++
Example 1: c++ switch multiple cases
#include <iostream>
using namespace std;
int main() {
// variable declaration
int input;
switch(input){
case 1: case 2: case 3: case 4:
//executes if input is 1, 2, 3, or 4
break;
case 5: case 6: case 7:
//executes if input is 5, 6, or 7
break;
default:
//executes if input isn't any of the cases
}
return 0;
}
Example 2: switch c++
switch(expression) {
case 1:
//equivalent to if(expression == 1){//do someting...}
//do something...
break;
//if case 1 is true the rest of the statments arn't
//evaluated because of the break
case 45:
//equivalent to else if(expression == 45){//do someting...}
//do something...
break;
// you can have any number of case statements and default has to be last
default :
// equivalent to else{//do someting...}
//do something...
}
switch(expression) {
case 1:
//equivalent to if(expression == 1){//do someting...}
//do something...
case 45:
//equivalent to if(expression == 45){//do someting...}
//do something...
default :
//always runs if there are no breaks in any of the cases
//do something...
}
//modification of answer by Homeless Hoopoe