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 set number of times or through a set range?
Scenario A - The for loop
for (int iLoop = 0; iLoop < int.MaxValue; iLoop++)
{
//Maybe do work here
//Test criteria
if (Criteria)
{
//Exit the loop
break;
}
//Maybe do work here
}
Advantages
Disadvantages
Scenario B - The do/while loop
int iLoop = 0;
do
{
//Increment the counter
iLoop++;
//Do work here
} while (Criteria);
or
int iLoop = 0;
while (Criteria)
{
//Increment the counter
iLoop++;
//Do work here
}
Advantages
Disadvantages
Just for completeness, you could also use option D:
for (int iLoop = 0; Criteria; iLoop++)
{
// work here
}
(where Criteria
is "to keep running")
the condition in a for
loop doesn't have to involve iLoop
. Unusual, though, but quite cute - only evaluates before work, though.
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++)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With