while(true); loop throws Unreachable code when isn't in a void

后端 未结 4 818
时光说笑
时光说笑 2020-12-29 20:28

I was doing some small programs in java. I know that if I write while(true); the program will freeze in this loop. If the code is like that:

4条回答
  •  庸人自扰
    2020-12-29 20:59

    The answer lies in the rules set out for reachability by the Java Language Specification. It first states

    It is a compile-time error if a statement cannot be executed because it is unreachable.

    And then

    A while statement can complete normally iff at least one of the following is true:

    • The while statement is reachable and the condition expression is not a constant expression (§15.28) with value true.
    • There is a reachable break statement that exits the while statement.

    and

    An expression statement can complete normally iff it is reachable.

    In your first example, you have a while loop that cannot complete normally because it has a condition which is a constant expression with value true and there is no reachable break within it.

    In your second and third examples, the expression statement (method invocation) is reachable and can therefore complete normally.


    So I suppose this is a java thing?

    The rules above are Java's rules. C++ probably has its own rules, as do other languages.

提交回复
热议问题