C++ Switch, Break, Default Statements
The switch
statement in C++ is used to control the flow of execution based on the value of an expression. The switch
statement is a convenient alternative to multiple if...else
statements, especially when you have a large number of cases to test. The basic syntax of the switch
statement is as follows:
1switch (expression) 2{ 3 case value1: 4 statements; 5 break; 6 case value2: 7 statements; 8 break; 9 ... 10 default: 11 statements; 12}
The expression
in the switch
statement is evaluated and compared to the values specified in each case
statement. When a case
value matches the value of the expression, the statements associated with that case
are executed.
break statement
The break
statement is used to exit the switch
statement and continue with the next statement after the switch
statement.
default statement
The default
case is executed when none of the case
values match the value of the expression.
Let's take a look at two examples of the switch
statement in C++ and their output:
Example 1: Simple switch Statement with break
1#include <iostream> 2using namespace std; 3 4int main() 5{ 6 int number = 2; 7 8 switch (number) 9 { 10 case 1: 11 cout << "The number is 1." << endl; 12 break; 13 case 2: 14 cout << "The number is 2." << endl; 15 break; 16 case 3: 17 cout << "The number is 3." << endl; 18 break; 19 } 20 21 return 0; 22}
In the above example, the switch
statement is used to test the value of the number
variable. The value of the number
variable is 2, which matches the second case
statement. The output of the program will be:
1The number is 2.
Example 2: Simple switch Statement with default
1#include <iostream> 2using namespace std; 3 4int main() 5{ 6 int number = 4; 7 8 switch (number) 9 { 10 case 1: 11 cout << "The number is 1." << endl; 12 break; 13 case 2: 14 cout << "The number is 2." << endl; 15 break; 16 case 3: 17 cout << "The number is 3." << endl; 18 break; 19 default: 20 cout << "The number is not 1, 2, or 3." << endl; 21 } 22 23 return 0; 24}
In the above example, the switch
statement is used to test the value of the number
variable. The value of the number
variable is 4, which does not match any of the case
values. The output of the program will be:
1The number is not 1, 2, or 3.