When using a switch()
statement, you add break;
in between separate case:
declarations. But what about the last one?
Normally I just leave it off, but I'm wondering if this has some performance implication I'm not thinking about?
I've been wondering about this for a while and don't see it asked elsewhere on Stack-O, but sorry if I missed it.
I'm mainly asking this question regarding Javascript, although I'm guessing the answer will apply to all switch()
statements.
The break KeywordIt is not necessary to break the last case in a switch block. The block breaks (ends) there anyway. Note: If you omit the break statement, the next case will be executed even if the evaluation does not match the case.
The break statement is used inside the switch to terminate a statement sequence. The break statement is optional. If omitted, execution will continue on into the next case. The default statement is optional and can appear anywhere inside the switch block.
Can the last case of a switch statement skip including the break? Even though the last case of a switch statement does not require a break statement at the end, you should add break statements to all cases of the switch statement, including the last case.
Answer 533416ba631fe960060022a4 No. return jumps back directly to the function call returning the value after it and everything (in a function) that is after an executed return statement is ignored. So return itself can act as a break statement for functions and no further break is required.
Performance should not be a consideration at all. Even if some language or implementation has a performance difference that's measurable in a micro-benchmark, it would never cause a real-world performance issue.
I think the most important issue is consistency and maintainability. If you leave off the last break
and then another developer adds another case statement without realizing you left off the break
, the behavior would change. It's really the second developer's fault for not noticing the break
is missing, but it could have been avoided by being consistent and having the break
on all case
clauses.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With