I saw a similar piece of perl code in the code base and wanted to know if this (setting i=100) was an OK way to get out of the for loop? Are there any pitfalls to this?
int a[100];
...
bool check_if_array_contains_29()
{
bool result = false;
for(int i=0; i<100; ++i)
{
if(a[i] == 29)
{
result = true;
i = 101;
}
}
return result;
}
This is more like what I would do.
bool check_if_array_contains_29()
{
bool result = false;
for(int i=0; i<100 && !result; ++i)
{
if(a[i] == 29)
{
result = true;
}
}
return result;
}
Edit -1:
I am not looking for a oneliner in perl to achieve the functionality. The real code (functionality) was much more complex. This is just an example that I simplified to explain my point(early termination of for loop).
Why wouldn't you just do this:
bool check_if_array_contains_29()
{
for(int i=0; i < 100; ++i)
{
if (a[i] == 29)
return true;
}
return false;
}
Edit:
I know some people feel that multiple return statements are just horrible and should be avoided at all costs, but to me, having multiple returns in a method like the one presented makes the code easier to read and follow.
Edit 2:
Additional versions so that if the method needs to have some side effects or perform some additional operations you can use a break statement, or you can adjust the for loop conditional, or you could add some labels and some gotos.
bool check_if_array_contains_29_take2()
{
bool result = false;
for (int i=0; i < 100; ++i)
{
if (a[i] == 29)
{
result = true;
break;
}
}
// Do Other Stuff
return result;
}
bool check_if_array_contains_29_take3()
{
bool result = false;
for (int i=0; !result && i < 100; ++i)
{
result = a[i] == 29;
}
// Do Other Stuff
return result;
}
// Special edition for those who can't get enough goto
bool check_if_array_contains_29_and_do_more_stuff_without_early_return()
{
bool result = false;
for (int i=0; i < 100; ++i)
{
if (a[i] == 29)
{
result = true;
break;
}
}
if (!result)
goto error;
// Do some other stuff in the code here
goto done;
done:
return result;
error:
result = false;
goto done;
}
What's wrong with break or simply return true inside the loop? It clearly conveys intent, and doesn't rely on the loop condition.
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