Fall through is a type of error that occurs in various programming languages like C, C++, Java, Dart …etc. It occurs in switch-case statements where when we forget to add a break statement and in that case flow of control jumps to the next line. Due to this when any case is matched with the specified value then control falls through to subsequent cases until a break statement is found. In C++, the error is not found on fallthrough but in languages like Dart, an error occurs whenever a fallthrough occurs.
It is not always necessary to avoid fallthrough, but it can be used as an advantage as well.
Below is the program to illustrate how fall-through occurs:
this is two this is three this is default
Explanation: In the above code, there is no break statement so after matching with the 2nd case the control will fall through and the subsequent statements will also get printed.
How to Avoid Fall Through?
To avoid Fall through, the idea is to use a break statement after each and every case so that after matching it goes out of the switch statement and control goes to the statement next to the switch statement.
Below is the program to illustrate how to avoid the fall through:
this is two