Java编译器如果我使用while true,则不会抱怨“没有返回语句”。

huangapple go评论55阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年6月22日 16:21:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76529887.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定