Use the switch
statement to specify which of several code blocks should be run.
Syntax:
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
This is how it functions:
- The
switch
expression is only once evaluated. - The values in each scenario are compared to the value of the expression.
- If there is a match, the matching piece of code is executed
- The
break
anddefault
keywords are optional; more information will be given later in this chapter.
The following Example identifies the name using a number:
#include <iostream> using namespace std; int main() { int day = 4; switch (day) { case 1: cout << "Rohit"; break; case 2: cout << "Ram"; break; case 3: cout << "Papun"; break; case 4: cout << "Google"; break; case 5: cout << "Rupesh"; break; } return 0; }
OUTPUT:
Google
The break Keyword
C++ exits the switch block when it encounters the break
keyword.
This will halt further code execution and case testing within the block.
When a match is made and the work is over, a break
is necessary. More testing is not necessary.
A break
“ignores” the execution of the entire rest of the switch
block’s code, which can save a significant amount of time during execution.
The default Keyword
If there is no case match, the default
keyword defines some code to execute:
#include <iostream> using namespace std; int main() { int day = 4; switch (day) { case 6: cout << "Today"; break; case 7: cout << "Yesterday"; break; default: cout << "Day after tomorrow"; } return 0; }
OUTPUT:
Day after tomorrow