Definition of switch statement, general form, keywords used in switch statement (such as break and default ) with example are in this slide.
Size: 352.34 KB
Language: en
Added: Apr 18, 2021
Slides: 11 pages
Slide Content
Switch cases Presented by BARANI G. 1
Switch cases: The switch statement evaluates an integral expression and chooses one of several execution paths based on the expression’s value. In other words, a Switch statement provides a convenient way of selecting among a (possibly large) number of fixed alternatives. 2
General form: switch ( expression ) { case x: // code block break ; case y: // code block break ; default : // code block } 3
How switch statements work: The switch expression is evaluated once. The value of the expression is compared with the values of each case . If there is a match, the associated block of code is executed. The break and default keywords are optional. 4
Flow chart of switch statement: 5
The break keyword: When C++ reaches a break keyword, it break out of the switch block. This will stop the execution of more code and case testing inside the block. When match is found, and the job is done, it’s time for a break . There is o need for more testing. A break can save a lot of execution time as it ignores the execution of all the rest of the code in the switch block. 6
The default keyword: The default code specifies some code to run if there is no case match. The default keyword must be used as the last statement in the switch , and it does not need a break . 7
Example: Day of the week #include <iostream> using namespace std; int main () { int day = 5 ; switch (day) { case 1 : cout << "Monday " ; break ; case 2 : cout << "Tuesday" ; break ; 8
case 3 : Cont … cout << "Wednesday" ; break ; case 4 : cout << "Thursday" ; break ; case 5 : cout << "Friday" ; break ; case 6 : cout << "Saturday" ; break ; 9