Which loop to use, for or do/while?

后端 未结 13 978
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:52

    I'd tend to use for if I'm actually using the counter in the loop, say as an index into an array, and as part of the criteria, i.e. "stop at the end of the array" rather than "just don't overflow".

    If I'm looping over something with unknown length, such as lines in a file, or just maintaining the counter to use the total after the loop, then I'll use do or while.

    However, it really comes down to what's more readable for a particular situation. I expect that you'd struggle to tell from the compiled IL which version was used.

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