11

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.

user2009750
  • 3,169
  • 5
  • 35
  • 58
  • @pronox.. for(i=0;i<10;i++) Here some initialization and condition is there but for(;;) no condition ,nothing.. So infinite loop. – Revan Feb 20 '14 at 17:30
  • 1
    thanks but what is was looking for is cleared by @dasblinkenlight's answer. – user2009750 Feb 20 '14 at 17:37
  • @pronox: So your question is about C? Then you should tag it as such. – Felix Kling Feb 20 '14 at 17:38
  • The behavior is mirrored in ECMAScript, Perl, and C++ as well as C, and in each case, it's a design decision for the language, not just an unintended consequence. You don't see `if()...` defaulting to true, or `while()...` defaulting to infinite. `for` was designed in each of those languages to intentionally have that behavior. – DavidO Feb 20 '14 at 17:40

5 Answers5

15

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.

Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Thanks i was wondering how is no expression replaced by true or none zero constant. You standard clears this... – user2009750 Feb 20 '14 at 17:35
1

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

Kapol
  • 6,383
  • 3
  • 21
  • 46
0

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.

10land
  • 195
  • 7
0

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.

Emu
  • 5,763
  • 3
  • 31
  • 51
-8

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.

user989056
  • 1,275
  • 2
  • 15
  • 33