Here’s a philosophical question. Let’s say you’re searching an array. Is it clearer to use a for
loop and break
when you find the element, or is it better to use a while
loop and break if you hit the end of the array?
Most of us would likely use the for
loop, but it wouldn’t be wrong to use the while
- maybe just unexpected.
But what if you had forgotten that while
loops even exist? An anonymous submitter found this, and distilled its essence for us:
for (int i = 0; i < int.MaxValue, i++)
{
// body of the loop, does not depend on i
if ( /* some condition, does not depend on i */)
break;
}
At first glance, this seems almost like one of those “search the array” loops, where you break upon finding the element. But that’s not what this is. This iterates up to int.MaxValue
times, and no internal iteration ever cares about what i
holds.
This is almost a while loop. It won’t run forever, but it’ll run for a real long time before giving up. Our submitter noticed because of a large pile of “unused variable” warnings- pretty much every place where you should use a while loop, this developer used the for/break
construct.
The upshot, I suppose, is that at least it wasn’t a for-case.