In this C++ tutorial, you will learn the syntax of switch statement, execution flow diagram, and its usage with example programs.
C++ Switch
In C++, Switch statement executes one of the many code blocks based on the value of an expression.
Syntax of switch statement
Following is the syntax of switch statement in C++.
switch (expression) { case value1: // code block break; case value2: // code block break; default: // code block }
Working of Switch Statement
- Start of switch statement. The expression is evaluated to a value.
- This value is then compared to each
case
value. - If it finds a match, corresponding block is executed.
- break statement at the end of case block is optional. After executing a block, execution comes out of the loop because of break. If no break statement is given, all the case blocks and default block, next to this block, are executed.
- default block is optional. If expression value does not match any of the case values, default block is executed.
Check the following flow diagrams for detailed working of break statements at the end of case blcoks, and default block.
Flowchart or Flow-Diagram
Following is the execution flow diagram of switch statement with break statement for each of the case blocks.
Following is the execution flow diagram of switch statement without break statement for case blocks.
Examples
1. Simple example for switch statement
Following is an example of Switch statement in C++. In this example, we shall print if the name of weekday based on number.
C++ Program
#include <iostream> using namespace std; int main() { int day = 25; switch (day%7) { case 1: { cout << "Monday" << endl; break; } case 2: { cout << "Tuesday" << endl; break; } case 3: { cout << "Wednesday" << endl; break; } case 4: { cout << "Thursday" << endl; break; } case 5: { cout << "Friday" << endl; break; } default: { cout << "Off day" << endl; } } }
Output
Thursday
2. Switch statement without break
Following is an example of Switch statement in C++. We have not used break statement after end of case blocks. In this example, we shall print if the name of weekday based on number.
C++ Program
#include <iostream> using namespace std; int main() { int day = 24; switch (day%7) { case 1: { cout << "Monday" << endl; } case 2: { cout << "Tuesday" << endl; } case 3: { cout << "Wednesday" << endl; } case 4: { cout << "Thursday" << endl; } case 5: { cout << "Friday" << endl; } default: { cout << "Off day" << endl; } } }
Output
Wednesday Thursday Friday Off day
Conclusion
In this C++ Tutorial, we learned about C++ Switch statement, consequences of including and not including break statement after each case block, and also about default block.