10

Would any one please explain this instruction for me: for (;;)

I have encountered several kinds of these mark (like in ajax code of facebook and in concurrent stuff of Java).

Phương Nguyễn
  • 8,747
  • 15
  • 62
  • 96

6 Answers6

23

An infinite loop.

Each of the three parts of a for loop (for(x; y; z)) is optional.

So you can do this:

int i = 0;
for (; i < 20; ++i)

and it's perfectly valid, or

for (int i = 0; i < 20;) { ++i; }

or

for (int i = 0; ; ++i) { if (i < 20) { break; } }

and they're all valid.

You can also omit all three parts, with for(;;). Then you have a loop that:

  • does no initialization (the first part)
  • has no condition for stopping (the middle part)
  • does nothing after each iteration (the last part)

so basically an endless loop. It just does what it says in the loop body, again and again

jalf
  • 243,077
  • 51
  • 345
  • 550
  • See the Java Language Specification §14.14.1.2 http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.14.1.2 for reference: "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. " – Adam Rosenfield May 22 '10 at 15:08
  • 9
    This answer pretty much proves the awesomeness of the "No question is too simple" policy. :) – Bill the Lizard May 22 '10 at 15:34
6

It's an endless loop. For the specificion of the for statement, see here.

tangens
  • 39,095
  • 19
  • 120
  • 139
5

That's an infinite loop, similar to

while(true)
{
    ...
}
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
2

Its an infinite loop, seeing as the (non-existent) exit condition will never be false.

Any for loop without an exit condition will be infinite:

for (int x=0; ; x++) { }

Exactly the same as while (true), although a little less readable IMHO.

Gordon Gustafson
  • 40,133
  • 25
  • 115
  • 157
2

That's indeed an infinite loop. But in Java you should really prefer while (true) over for (;;) since it's more readable (which you probably already realize). The compiler will optimize it anyway. In JavaScript there's no means of a compiler and every byte over HTTP counts, that's the reason why for (;;) is preferred. It saves a few characters (bytes).

Uncle Iroh
  • 5,748
  • 6
  • 48
  • 61
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
2

The syntax for a for loop is

for (init-stmt; condition; next-stmt) {

}

So it is simply a for loop with no initial statement, next statement or condition. The absence of the exiting condition makes it infinite.

Martin Smith
  • 438,706
  • 87
  • 741
  • 845