break and switch appears to execute all case statements

前端 未结 4 1830
南笙
南笙 2020-12-21 02:45

In the latest stable release of Java and Eclipse (Kempler), entering the following code and executing it, assuming the package and class names exist:

package         


        
4条回答
  •  粉色の甜心
    2020-12-21 02:53

    The reason why switch works as it does is that this:

    switch(p){  
            case (1):
                x--;
            case (2):
                x = 2;
            case (3):
                x = 3;
            default:
                x++;
        }
    

    is really just syntactic sugar for this (basically):

    if (p == 1)
        goto .L1;
    else if (p == 2)
        goto .L2;
    else if (p == 3)
        goto .L3;
    else
        goto .L4;
    
    .L1:
        x--;
    .L2:
        x = 2;
    .L3:
        x = 3;
    .L4:
        x++;
    

    Java doesn't have a goto statement, but C does, and that's where it comes from. So if p is 2, it jumps to .L2 and executes all the statements following that label.

提交回复
热议问题