Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

According to this book I am reading:

Q What happens if I omit a break in a switch-case statement?

A The break statement enables program execution to exit the switch construct. Without it, execution continues evaluating the following case statements.

Suppose if I have codes looking like

switch (option}{
    case 1:
    do A;
    case 2:
    do B;
    default:
    do C;
    break;
}

Does this mean if I choose case 1, the A and C are done. If I choose case 2, B and C are done. If i choose neither, then only C is done.

if so, what happens if we omit the break after do C.

I assume these are bad programming practice, but I am curious what would happen to get a deeper understanding how it all works. Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
408 views
Welcome To Ask or Share your Answers For Others

1 Answer

You execute everything starting from the selected case up until you see a break or the switch statement ends. So it might be that only C is executed, or B and then C, or A and B and C, but never A and C


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...