I can only assume it's an infinite loop.
Can I leave out any of the three expressions in a for loop? Is there a default for each when omitted?
I can only assume it's an infinite loop.
Can I leave out any of the three expressions in a for loop? Is there a default for each when omitted?
Just like in C and C++ you can omit any of the three, or all three.
Yes, it's an infinite loop.
Examples:
for (; ;) { }
(aka: The Crab)
while (true) { }
do { } while (true)
Yes, that's an infinite loop. You can leave out any of the three expressions, though in my experience it's typically either the first or all 3.
There are no defaults. Nothing is initialised, nothing is incremented and there's no test for completion.
It's an infinitely loop. Effectively, its the same as this:
while (true)
{
}
It is indeed an infinite loop.
Under the hood the compiler/jitter will optimize this to (effectively) a simple JMP operation.
It's also effectively the same as:
while (true)
{
}
(except that this is also optimized away, since the (true) part of a while expression usually requires some sort of comparison, however in this case, there's nothing to compare. Just keep on looping!)
There are no defaults for first and third part (they default to nothing and it would work). The default for conditional expression is true
which will make for(;;)
effectively an infinite loop. (If the default was supposed to be false
, it would have been useless to have such a construct).
for (; ;) { }
is infinite loop, you are correct.
if you want to use it, then you have to put some condition in your loop body, so that it can exit out from loop.
for (; ;)
{
if (conditionTrue)
break;
else
continue;
}
Microsoft's C# Programmer's Reference says:
All of the expressions of the for statement are optional; for example, the following statement is used to write an infinite loop:
for (;;) {
...
}