The switch-case fall through

So, I am a Software Engineer at a reputed firm and still fell for the trap of fall-through feature of the switch-case statement.

Rule of thumb: Starting from the matched case, all statements are executed, unless a break statement is reached. After the break statement, the control is transferred to the statement next to the switch-case block. 

Here are some examples to test your understanding of switch-case:

The output of the example is AB. This is because there is no break statement and so all the statements are executed after the first match of case 0.

The output of the example is BCD. This is because there is no break statement and so 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 so, after the first match at case 0, all the statements are executed till the break statement.

The output of the example is AB. This is because there is a break statement at the end of case 2 so, after the first match at case 1, all the statements are executed till the break statement.

So basically, after the first time match, the switch-case falls-through all the statements. Although fall-through is important for grouping multiple cases, it has been criticized for its complexity. Some languages like C# don't allow blocks without break statement unless the block is empty.

Comments

Popular posts from this blog

DDoS Attack on Bitotsav '19 Website

Setting up Machine Learning environment on High Performance Computing Server

Computer Science and Engineering at Birla Institute of Technology, Mesra