Switch Case statements are an efficient alternative to if…else construct. Both the constructs i.e. if…else & switch case are similar and used to select & execute one of many available code blocks based on certain conditions. So, when to use switch case?
When the number of alternatives/options are high (say more than 4) an if else looks cluttered where as a switch case looks tidy, readable and to some extent performs better than if…else construct.
The following code sample will familiarize you with switch case syntax. Note: For this example if…else construct would have been equally good.
The example shows you a for loop to get integers starting from 1 to 20. The logic in the for loop checks each number from 1 to 20 using remainder operator. If the remainder is 0 after division with 2 we are printing is Even otherwise it’ll print is Odd.
Output of the above code sample:
When fallthrough keyword is used inside a switch case statement, the control automatically moves and execute the next code block. An example code with output is shown below for your reference.
The output is the reflection of a typical switch case behavior as expected. Just concentrate on the section where you’ve given the input as “Fri”. What happens here?
The output executes the matching statement based on the input and then the control also goes to the next statement because of the fallthrough effect.
Share it if you like it.