views:

469

answers:

10

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?

+1  A: 

Just like in C and C++ you can omit any of the three, or all three.

Dave Van den Eynde
+15  A: 

Yes, it's an infinite loop.

Examples:

for (; ;) { } (aka: The Crab)

while (true) { }

do { } while (true)

Alex Fort
+4  A: 

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.

Harper Shelby
A: 

It's an infinite loop :).

sjmulder
+2  A: 

There are no defaults. Nothing is initialised, nothing is incremented and there's no test for completion.

ChrisF
+3  A: 

It's an infinitely loop. Effectively, its the same as this:

while (true)
{
}
Dustin Campbell
+5  A: 

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!)

CraigTP
+2  A: 

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).

Mehrdad Afshari
+2  A: 

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;
}
Syed Tayyab Ali
A: 

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 (;;) {
   ...
}
JeffH