C# for loop syntax

前端 未结 4 1092
别那么骄傲
别那么骄傲 2021-01-18 18:56

I\'m working on some C# code that has loop syntax that I\'ve never seen before:

for (;;)
{
  //Do some stuff
}

What does a for loop without

相关标签:
4条回答
  • 2021-01-18 19:07

    That is an infinite loop. Like you stated, it will run until a part of it breaks (throws an exception or otherwise exists the loop) or the machine runs out of resources to support the loop.

    for (;;)
    {
       //do stuff
    } 
    

    Is just the same as:

    do
    {
       //do stuff
    }while (true)
    

    while(true)
    {
       //do stuff
    }
    
    0 讨论(0)
  • 2021-01-18 19:11

    This type of for loop is an infinite loop. It is the equivalent of while(true){stuff to be executed...}. It keeps on going until it hits a break, return, or a goto to a label outside the loop.

    A for loop has three parts, an initialization, a condition, and a block to be executed after the loop. Without a condition to be tested against, the loop will just keep on going.

    0 讨论(0)
  • 2021-01-18 19:12

    The syntax of a for loop is thus:

    for (condition; test; action)
    

    Any one of those items can be omitted (per the language spec). So what you've got is an infinite loop. A similar approach:

    while (true) { // do some stuff }
    
    0 讨论(0)
  • 2021-01-18 19:32

    for (;;)

    Short answer: It is an infinite loop which is equivalent to while(true)

    Long answer: for (initializer; condition; iterator) Structure of the for statement

    • initializer block: Do not initialize variable.
    • condition block: with no condition (means execute infinitely) => while true
    • iterator block: with no operation to any variable (no iterator)

    for(;;) example from official documentation

    0 讨论(0)
提交回复
热议问题