Skip to content
Advertisement

Get out of a foreach [closed]

My C++ teacher once told me that if I have to use a break to get out of a loop I didn’t think enough about the loop condition.

So did she (very good teacher btw) just fail to mention that foreach loops are an exception to this rule (which I have generally found to be true) or is there indeed a way to get out of a foreach loop without using a break?

I am asking in general, but most interesting for me would be for Java or PHP.

Edit:
In case I haven’t made this clear, I am wondering if there is a way to get out of a foreach-loop without using a break. Not sure what this whole commotion is about, what’s wrong with that question?

Advertisement

Answer

foreach loops don’t have any exit condition except for the implicit “when there are no more items to iterate over”, so it is not possible to break out of them early while avoiding break without using some sort of a terrible hack (e.g. throwing exception, modifying the iterated collection, setting a boolean flag dontContinue and checking it in each iteration, etc.).

For ordinary loops, there indeed always is an obvious way to avoid using break (stop the current iteration using continue or if, and put the early exit condition into loop’s condition), however whether such approach leads to a more readable code than using break is disputable.


In some cases, the reason for you to want to break out of a loop early is because you finished whatever task needed to be done, or found the needed item. In such cases, consider putting the particular functionality into a separate method and using return instead of break.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement