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:
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
whilestatement can complete normally iff at least one of the following is true:
- The
whilestatement is reachable and the condition expression is not a constant expression (§15.28) with valuetrue.- There is a reachable
breakstatement 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.