Hello everyone,
Quick question, is it proper to use the break function to exit many nested for loops? If so, how would you go about doing this? Can you also control how many loops the break exits?
Thanks,
-Faken
Hello everyone,
Quick question, is it proper to use the break function to exit many nested for loops? If so, how would you go about doing this? Can you also control how many loops the break exits?
Thanks,
-Faken
Breaking out of a for-loop is a little strange to me, since the semantics of a for-loop typically indicate that it will execute a specified number of times. However, it's not bad in all cases; if you're searching for something in a collection and want to break after you find it, it's useful. Breaking out of nested loops, however, isn't possible in C++; it is in other languages through the use of a labeled break. You can use a label and a goto, but that might give you heartburn at night..? Seems like the best option though.
AFAIK, C++ doesn't support naming loops, like Java and other languages do. You can use a goto, or create a flag value that you use. At the end of each loop check the flag value. If it is set to true, then you can break out of that iteration.
break will exit only the innermost loop containing it.
You can use goto to break out of any number of loops.
Of course goto is often Considered Harmful.
is it proper to use the break function[...]?
Using break and goto can make it more difficult to reason about the correctness of a program. See here for a discussion on this: Why Dijkstra suggested Premature-Loop-Exit Prohibition.
Other languages such as PHP accept a parameter for break (i.e. break 2;) to specify the amount of nested loop levels you want to break out of, C++ however doesn't. You will have to work it out by using a boolean that you set to false prior to the loop, set to true in the loop if you want to break, plus a conditional break after the nested loop, checking if the boolean was set to true and break if yes.
No, don't spoil it. This is the last remaining stronghold for using GOTO.
Another approach to breaking out of a nested loop is to factor out both loops into a separate function, and return
from that function when you want to exit.
Of course, this brings up the other argument of whether you should ever explicitly return
from a function anywhere other than at the end.
See if you can restructure your loops so it's not needed.
If it really is, use setjmp/longjmp in C or throw an custom execption in C++