switch-case statement without break

后端 未结 7 1679
鱼传尺愫
鱼传尺愫 2021-02-04 01:44

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 swi

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-04 01:59

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

    if your option is 1 it executes everything til it finds the break keyword... that mean break end the excution of the switch --> case Output :A then B then C so it is recommended to put break after each case like :

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

    if your option is 1 the Output will be : just A ...

    note: default doesn't need a break;

提交回复
热议问题