gpt4 book ai didi

java - break 和 switch 似乎执行所有 case 语句

转载 作者:搜寻专家 更新时间:2023-11-01 01:43:34 24 4
gpt4 key购买 nike

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

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 语句中。现在我认为问题在于它是如何编译的。例如,我目前的信念是, boolean 值在内部跟踪 case 语句是否等于该值。如果是,则 boolean 值为真,所有 case 语句都将被视为真,直到找到中断。这是有道理的,但我仍然想知道这背后是否还有其他原因,或者我的假设是否完全错误。

最佳答案

switch 如此工作的原因在于:

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

真的只是语法糖(基本上):

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 - break 和 switch 似乎执行所有 case 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19796711/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com