문제

Like many other question explained that while(true) {} is an infinite loop and so is for( ; ;) my question is while(true) makes sense the conditions is always true but there is no vivid condition true/false in for( ; ;) so how is the later an infinite loop.

도움이 되었습니까?

해결책

According to Java Language Specification, section 14.14.1.2:

for ( ForInitopt ; Expressionopt ; ForUpdateopt ) Statement

If the Expression is not present, or it is present and the value resulting from its evaluation (including any possible unboxing) is true, then the contained Statement is executed.

Since the standard treats missing expressions and expressions evaluating to true in the same way, the for loop with the missing expression is equivalent to an infinite loop.

다른 팁

You do not specify any condition to continue the loop, so it is executed forever.

The three parts of for loop: variable initialization, condition and variable update are optional. If the condition is absent, it is evaluated as true. The loop continues till something else in for loop block stops it. Since in your example for loop is empty, it is an infinite loop.

A loop becomes infinite loop if a condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the for loop are required, you can make an endless loop by leaving the conditional expression empty. When the conditional expression is absent, it is assumed to be true.

The loop for( ; ;) is garbage. If that provides an infinite loop, it is at the control of that specific languages compiler that turns it into a infinite loop.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top