So, I am a Software Engineer at a reputed firm and still fell for the trap of the fall-through feature of the switch-case statement.
Rule of Thumb:
- Starting from the matched case, all statements within the switch block are executed, unless a break statement is encountered.
- After the break statement, or if no break is encountered within the matched case, control is transferred to the statement following the entire switch block.
Examples:
Here are some examples to test your understanding of switch-case:
The output of the example is BCD. This is because there is no break statement, and therefore all the statements are executed after the first match of case 1.
The output of the example is AB. This is because there is a break statement at the end of case 1. Therefore, after the first match at case 0, all the statements are executed until the break statement.
The output of the example is AB. This is because there is a break statement at the end of case 2. Therefore, after the first match at case 1, all the statements are executed until the break statement.
Comments
Post a Comment