While switch statements have been with C++ since day one, the decision to make them default their control flow to a fall through state makes them hard to troubleshoot.Switch statement is a control statement that allows us to choose only one choice among the many given choices. It is a control statement used to make a selection between many alternatives.
Syntex :-
switch (expression) {
case 1:
// code block
break;
case 2:
// code block
break;
case 3:
// code block
break;
default:
// code block
}
Q.) A simple program to understand switch Statement.
#include < iostream>
using namespace std;
int main() {
int a = 1;
switch (a) {
case 1:
cout << n1 << "My Choice is 1";
break;
case 2:
cout << n1 << "My Choice is 2";
break;
case 3:
cout << n1 << "My Choice is 3";
break;
default:
// Variable "a" doesn't match any case
cout << "Invalid! The Choice is not correct";
break;
}
return 0;
}