Which loop to use, for or do/while?

后端 未结 13 974
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:28

    I ususually use for, cause it's simple. I use while when counter is needed after or before loop or if using for is impossible.

    0 讨论(0)
  • 2021-01-19 23:29

    How about the best of both worlds:

    for (int iLoop = 0; iLoop < int.MaxValue && !Criteria; iLoop++)
    

    Edit: Now that I think about it, I suppose comparing against int.MaxValue wasn't part of the criteria, but something to emulate an endless for loop, in that case you could just use:

    for (int iLoop = 0; !Criterea; iLoop++)
    
    0 讨论(0)
  • 2021-01-19 23:32

    There's no reason not to use a for loop in this case. Even if you have other criteria, it's perfectly valid to write:

    for (int iLoop = 0; iLoop < int.MaxValue && Criteria; iLoop++) { ... }
    
    0 讨论(0)
  • 2021-01-19 23:32

    Personally I would go with the for loop.

    It is better to read, more commonly used and very optimized.

    for (int iLoop = 0; iLoop < int.MaxValue && !Criteria; iLoop++)
    {
    // Do Work
    }
    

    Edit: int.MaxValue && !Criteria <- a definietely better approach than my initial one ;)

    0 讨论(0)
  • 2021-01-19 23:33

    You can always add the exit criteria to for loop:

    for (int iLoop = 0; iLoop < int.MaxValue && Criteria; iLoop++)
    {
      //Maybe do work here
    }
    

    I would really go for whatever looks most readable in your particular case.

    0 讨论(0)
  • 2021-01-19 23:34
    for (int iLoop = 0; iLoop < int.MaxValue && !Criteria; iLoop++) {
        //Do work here...
    }
    
    0 讨论(0)
提交回复
热议问题