Which loop to use, for or do/while?

后端 未结 13 991
Happy的楠姐
Happy的楠姐 2021-01-19 23:02

Using C# (or VB.NET) which loop (for loop or do/while loop) should be used when a counter is required?

Does it make a difference if the loop should only iterate a se

13条回答
  •  攒了一身酷
    2021-01-19 23:42

    Instead of a dummy criteria in the for loop, you can use the actual criteria that you want to use for the loop:

    Scenario A2 - the for loop with custom criteria:

    for (int iLoop = 0; Criteria; iLoop++) {
    
      // do work here
    
    }
    

    This is equivalent to:

    {
       int iLoop = 0;
       while (Criteria) {
    
          // do work here
    
          iLoop++;
       }
    }
    

    If you have a loop counter, you should generally use a for loop to make that clearer.

提交回复
热议问题