When C reaches a break keyword, it breaks out of the switch block.This will stop the execution of more code and case testing inside the block.When a match is found, and the job is done, it's time for a break. There is no need for more testing....
The switch statement evaluates an expression. The value of the expression is then compared with the values of each case in the structure. If there is a match, the associated block of code is executed. The switch statement is often used together with a break or a default keyword (or both)...
It is possible to have multiple values for each case in the switch statement:Syntax switch expression { case x,y: // code block if expression is evaluated to x or y case v,w: // code block if expression is evaluated to v or w case z: ... default: // code block if...
A break can save a lot of execution time because it "ignores" the execution of all the rest of the code in the switch block.The default KeywordThe default keyword specifies some code to run if there is no case match:Example int day = 4; switch (day) { case 6: System.out.println(...
case 1: printf("Monday"); break; case 2: printf("Tuesday"); break; case 3: printf("Wednesday"); break; case 4: printf("Thursday"); break; case 5: printf("Friday"); break; case 6: printf("Saturday"); break; case 7: printf("Sunday"); break;}// Outputs "Thursday" (day 4)...
case0: text ="Today is Sunday"; break; default: text ="Looking forward to the Weekend"; } The result of text will be: Today is Sunday Try it Yourself » Thedefaultcase does not have to be the last case in a switch block:
Thebreakanddefaultkeywords are optional, and will be described later in this chapter The example below uses the weekday number to calculate the weekday name: Example intday =4; switch(day) { case1: cout <<"Monday"; break; case2: