开发者

What does for(;;) mean in C#

I see the following code

for (;;)
{
/开发者_Python百科/body...
}

What does it mean?


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.


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.


This would cause an infinite loop. See MSDN


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.


while(true) { /* body */ }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜