英文:
Java compiler doesn't complain that `No return statement` if I use while true
问题
以下是翻译好的部分:
我有以下代码,编译器应该投诉“没有返回语句”,但代码运行正常。
如果我删除while(true)
代码块,然后编译器会正常工作并投诉“没有返回语句”,我想知道编译器在这里是如何工作的。
public class ReturnTest {
public static void main(String[] args) {
System.out.println(check());
}
public static boolean check() {
int i = 0;
while (true) { //(1)
if (i >= 100) {
return true;
} else {
i++;
}
}
}
}
英文:
I have following code, the compiler should complain that No return statement
, but the code works fine.
If I remove the while(true)
code block, then the compiler works and complains No return statement
, I would like to know how the compiler works here.
public class ReturnTest {
public static void main(String[] args) {
System.out.println(check());
}
public static boolean check() {
int i = 0;
while (true) { //(1)
if (i >= 100) {
return true;
} else {
i++;
}
}
}
}
答案1
得分: 2
编译器意识到:while语句要么返回,要么继续循环(然后稍后返回)。由于while语句在方法中实际上是终结的(并且无法将执行传递到更深层),因此在该while语句下面的任何代码都被视为“死代码”(因为无法到达),因此不需要返回。
英文:
The compiler realizes: The while statement either returns, or continues looping (and returns later). Since the while statement is effectively terminal in the method (and can't pass the execution further down), any code below that while statement is considered "dead code" (since it can't be reached), and thus a return isn't needed.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论