break和switch似乎执行所有case语句 [英] break and switch appears to execute all case statements

查看:132
本文介绍了break和switch似乎执行所有case语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java和Eclipse(Kempler)的最新稳定版本中,输入以下代码并执行它,假设包和类名存在:

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);
    }
}

这打印值4.原来,我认为它应该打印2因为我认为即使没有break语句,每段代码仍然保存在case语句中。现在我认为问题在于如何编译。例如,我目前的信念是内部布尔值跟踪case语句是否等于该值。如果是,则布尔值为true,所有case语句将被视为true ,直到找到中断为止。这是有道理的,但我仍然想知道这背后是否有其他原因,或者我的假设完全错误。

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.

推荐答案

开关正常工作的原因是:

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没有 goto 语句,但C确实如此,而这就是它的来源。因此,如果 p 为2,它将跳转到 .L2 并执行该标签后面的所有语句。

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.

这篇关于break和switch似乎执行所有case语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆