Why is there a need to ```break;``` in a Switch?


#1

Skip to where it says “question” if you want to get to the question.

Hello! I have a quick question about the need of the use of break; in a switch. If you’ve done the Conditionals lesson(s), then you know how to create and use a switch -

switch (data) {
    case matchesData:
        actions;
        break;
    case matchesData2:
        actions;
        break;
    default:
        actions;
        break;

Basically, each case is tested against the data type between the parentheses of the switch and if the two match then that branch of code is executed. However, you’ll notice that after each case you’ll need to put a break;. Break is what is used to ‘break’ out of a block of code, like each case. When you put a break; the computer stops executing any code inside wherever you put the break and moves on to whatever needs to be executed next.

However, if you look at an if…else -

if (blah operator blah2) {
    actions;
} else if (ah operator ah2) {
    actions;
} else {
    actions;
}

There is no need for any breaks.

QUESTION
Why? Why do we need breaks in switches? I know it probably has something to do with how switches and if…elses work, but why are they different? Why is there a need for break;s in switches? Couldn’t they be created so that they could just stop executing code when it moves on to the next case?


#2

Immediately after asking my question, I already have thought of a possible answer - in an if…else, each branch of action is separated by curly braces, but in switches, they are only separated by case:, which would be assumed to be another action.

Is this the reason, or is there something else? Thanks.


#3

Pretty much, yes. break is a control flow tool because it diverts to the first instruction after the switch.