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:
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.