Recently, when developing a calculator program, I found myself using goto
multiple times to restart a for loop.
Example:
StartLoop:
for (int i = 0; i < length; i )
{
if (items[i] == condition)
{
//Do something
goto StartLoop:
}
}
I know that goto
should be avoided but what other way would I have to restart the loop?
CodePudding user response:
Just set the value of i
:
int length = 9;
for (int i = 0; i < length; i )
{
Console.WriteLine(i);
if (i == 7)
{
i = -1;
}
}
0
1
2
3
4
5
6
7
0
1
2
3
4
5
6
7
0
1
2
3
4
5
...
CodePudding user response:
As per a comment from /u/Tim Schmelter, it's probably going to be clearer to split the logic into multiple methods.
If you put the loop into a bool-returning method, you can then return a value which indicates whether the loop was terminated prematurely. There's a myriad ways to do that; here's one example:
void processItemsUntilComplete(int[] items)
{
static bool condition(int item) => item == 42;
while (!processItemsUntil(items, condition))
{
// Keep looping until processItems() returns true to indicate that it completed.
}
}
/// <summary>Processes items until a certain condition occurs.</summary>
/// <returns>True if all the items were processed; false if the processing was interrupted because the condition was true.</returns>
bool processItemsUntil(int[] items, Predicate<int> condition)
{
foreach (var item in items)
{
if (condition(item))
return false;
// Other processing.
}
return true;
}