我不明白break語句是如何「知道」它是在一個循環內部才能退出的。
break
聲明不知道它在switch
或循環語句中。編譯器驗證break
語句在switch
或循環語句內。如果在循環語句中遇到break
語句而不是,它將發出編譯時錯誤。
如果沒有直接封閉方法,構造函數或初始化程序switch
,while
,do
,或for
語句包含break語句,就會發生編譯時錯誤。
如果編譯器能夠驗證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
編譯器知道其中環是。 –
@HotLicks編譯器應該是無所不知的:) – hexafraction