switch-case statement without break

后端 未结 7 1680
鱼传尺愫
鱼传尺愫 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:50

    Try yourself - Run the code using ideone available here.

    #include 
    
    void doA(int *i){
        printf("doA i = %d\n", *i);
        *i = 3;
    }
    
    void doB(int *i){
        printf("doB i = %d\n", *i);
        *i = 4;
    }
    
    void doC(int *i){
        printf("doC i = %d\n", *i);
        *i = 5;
    }
    
    int main(void) {
        int i = 1;
        switch(i){
            case 1:
                doA(&i);
            case 2:
                doB(&i);
            default:
                doC(&i);
                break;
        }
        return 0;
    }
    

    Output:

    doA i = 1
    doB i = 3
    doC i = 4
    

    Note:

    • It will execute all the options from the selected case until it sees 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
    • If you change the value of the variable analysed in switch inside the handle function (e.g doA), it does not affect the flow as describe above

提交回复
热议问题