"fallthrough" used in switch block, will transfer the execution to the next case's first statement without evaluating the next case statement. In real world, why do we need it? If at all we had to execute the next case block, we could have combined that code in the evaluated case already. Why do we really need "fallthrough"? What is its significance?
Combining the 2 cases into a single one is not equivalent with 2 separate cases where the first ends with a fallthrough
.
switch {
case conditionA:
statementA()
fallthrough
case conditionB:
statementB()
}
In this example statementB()
is executed if conditionA
evaluates to false
and conditionB
evaluates to true
. If you would combine them:
switch {
case conditionA:
statementA()
statementB()
}
Here statementB()
is executed only if conditionA
evaluates to true
, and that's all. This is not the same as the first example.
Obviously you can't include conditionB
in the case expression as statementA
must not depend on conditionB
(if we want an equivalent transformation).
All in all, this is just a "tool" which you may or may not use. You can achieve the same in other ways (if
statement), but this may be convenient in some cases.
In many languages you are required to use a break
statement if you don't want this "fallthrough" behavior, so many people might get accustomed to it. Although most often switches are used not to fallthrough, so this became the default in Go, but if you need the other logic, you have the option with fallthrough
.
The question Why do we really need "fallthrough"? is equivalent in those languages with Why do we need "break" to be optional and not mandatory?