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).
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).
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:
so basically an endless loop. It just does what it says in the loop body, again and again
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.
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).
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.