gpt4 book ai didi

java - Java如何知道跳出循环时跳转到哪里?

转载 作者:IT老高 更新时间:2023-10-28 21:03:16 24 4
gpt4 key购买 nike

while (condition) {

if (condition) {
statement1;
statement2;

break;
} else {
statement3;
statement4;
}

}

通过在 if 子句中使用 break,我们确保循环停止并退出。

我不明白 break 语句是如何“知道”它在循环中首先退出的,或者它是如何“知道”跳转到哪里的。这是怎么发生的?

最佳答案

I don't understand how the break statement "knows" that it is within a loop for it to exit out of in the first place.

break 语句不知道它在 switch 或循环语句中。编译器验证 break 语句在switch 或循环语句中。如果在循环语句中遇到 notbreak 语句,它将发出编译时错误。

If no switch, while, do, or for statement in the immediately enclosing method, constructor, or initializer contains the break statement, a compile-time error occurs.

如果编译器能够验证 break 语句是否在 switch 或循环语句中,它将发出 JVM 指令立即突然跳转到第一条语句在最近的封闭循环之后。

因此:

for(int i = 0; i < 10; i++) {
if(i % 2 == 0) {
break;
}
}

会被编译器翻译成:

0:  iconst_0        # push integer 0 onto stack
1: istore_1 # store top of stack in local 1 as integer
# i = 0
2: iload_1 # push integer in local 1 onto stack
3: bipush 10 # push integer 10 onto stack
5: if_icmpge 23 # pop and compare top two (as integers), jump if first >= second
# if i >= 10, end for
8: iload_1 # push integer in local 1 onto stack
9: iconst_2 # push integer 2 onto stack
10: irem # pop top two and computes first % second and pushes result
# i % 2
11: ifne 17 # pop top (as integer) and jump if not zero to 17
# if(i % 2 == 0)
14: goto 23 # this is the break statement
17: iinc 1, 1 # increment local 1 by 1
# i++
20: goto 2 # go to top of loop
# loop
23: return # end of loop body

关于java - Java如何知道跳出循环时跳转到哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17800348/

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