break and switch appears to execute all case statements

纵饮孤独 提交于 2019-11-28 08:58:31

问题


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 some_package;

public class what_the_heck {

    public static void main(String[] args) {
        int p = 2;
        int x = 1;
        switch(p){  
            case (1):
                x--;
            case (2):
                x = 2;
            case (3):
                x = 3;
            default:
                x++;
        }
        System.out.println(x);
    }
}

This prints the value 4. Originally, I thought it should print 2 because I thought that even if there were no break statements, each piece of code is still held in a case statement. Now I think that the issue lies in how it is compiled. For example, my current belief is that internally a boolean keeps track of whether or not a case statement was equal to the value. If it was, then the boolean is true and all case statements will be treated as true until a break is found. This makes sense, but I am still wondering if there are other reasons behind this, or if I am entirely wrong in my assumption.


回答1:


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.




回答2:


When you don't put a break the switch will execute all other cases that are underneath the entry point

So it actually executes

 x = 2;
 x = 3;
 x++;
 print(x);
 System.out.println(x);

Tks to Pshemo here is a link to the specification of the switch statement




回答3:


If a condition in a case block is true and there is no return or break, all the other case blocks will be executed regardless if the are true or not.

For a rule of thumb always put a break or return at the end of a case block and you will be 90% right.

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



回答4:


If you want to skip all following cases you need to put a break; at last of this case block or all following case blocks are executed, too.

Have a look: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html



来源:https://stackoverflow.com/questions/19796711/break-and-switch-appears-to-execute-all-case-statements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!