tags:

views:

287

answers:

5

I see the following code

for (;;)
{
//body...
}

What does it mean?

+5  A: 

This would cause an infinite loop. See MSDN

Marek Karbarz
+15  A: 

It's a loop with no starting value or conditions, so it will go forever, similar to

while (true)
{
    // body...
}

You'd need to use a break; statement to get out of the loop.

Jarrett Meyer
Or a return. Or an exception (not that you should do that).
Mark Byers
It's also valid with all C languages.
Sergej Andrejev
In C, it would be like this while (1){ .... }
tommieb75
A: 
while(true) { /* body */ }
Yuliy
+4  A: 

It repeats the body forever.

Here is the disassembly:

IL_0001:  br.s        IL_0005
IL_0003:  nop         
IL_0004:  nop         
IL_0005:  ldc.i4.1    
IL_0006:  stloc.0     
IL_0007:  br.s        IL_0003

LINQPad is a very nice little utility that lets you explore questions like this. Run linqpad, set the language dropdown to "C# statements", put in your code snippet, click run, click the "IL" button above the output window. If you don't know IL assembly, just hover over each opcode and an English description pops-up. For this specific example, you will need to click stop to see the results buttons, because this example loops forever.

Thanks for the linqpad link. Looks *very* cool.
Ben Aston
+9  A: 

A loop like this:

for (i = 0; i < 4; i++) { ... }

is the same as:

i = 0;
while (i < 4) {
   ...
   i++;
}

So, a loop like this:

for (;;) { ... }

is a shorter form for:

for (;true;) { ... }

so it becomes the same as:

;
while (true) {
   ...
   ;
}

I.e. the initialisation and modification are optional, and when the condition is omitted it simply evaluates to true.

Guffa