views:

1281

answers:

9

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

A: 

The break statement terminates the execution of the nearest enclosing do, for, switch, or while statement in which it appears. Control passes to the statement that follows the terminated statement.

from msdn.

Rob
A: 

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.

Nick Lewis
It's not strange at all. If you're iterating over a collection to look for something (and don't have a faster way of searching), there's no point finishing the loop. (as one example)
Joe
+9  A: 

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.

phantombrain
Don't be afraid to use a `goto` if that is the best option.
Hooked
I'm a new C++ programmer (and one without any formal programming training) thus after reading about people's rants on goto. I'm hesitant on using it in fear my program might just suddenly explode and kill me. Other than that, when i used to write programs on my ti-83 (in boring math class of course), the functions the basic editor provided required the use of goto's.
Faken
I seem to remember reading that many compilers give up on optimizing loops when a goto is present...
Steven Sudit
@Faken: Two types of programmers use `goto`: Bad programmers, and pragmatic programmers. The former are self explanatory. The latter, which you would fit into if you choose to use them well, use a so called "evil" concept when it is the lesser of (two) evils. Read this for a better understanding of some C++ concepts that you might need to use from time to time (macros, goto's, preprocessor, arrays): http://www.parashift.com/c++-faq-lite/big-picture.html#faq-6.15
Hooked
@Faken: There's nothing wrong with using goto. It's _misusing_ a goto that is troublesome.
Everyone
@Hooked: That's right, except that using `goto` rarely ever is the best option. Why not put the loops into their own function (`inline`, if you're concerned about speed) and `return` from this?
sbi
+1  A: 

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.

Karl Voigtland
A good answer in that it explains that "goto is harmful" meme is strongly tied to the more generalized "control flow interruption is harmful" statement. It is meaningless to say "goto is harmful", and then turn around and recommend using `break` or `return`.
Pavel Minaev
@Pavel: `break` and `return` have the advantage over `goto` that you don't need to hunt for a label in order to find where they go. Yes, underneath they are some kind of `goto`, but a very restricted one. They are a lot easier to decipher by a programmer's pattern-matching brain than the unrestricted `goto`. So IMO they are preferable.
sbi
@sbi: True, but break is still not part of structured programming. It is just better tolerated than a `goto`.
Hooked
A: 

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.

Patrick Daryll Glandien
+18  A: 

No, don't spoil it. This is the last remaining stronghold for using GOTO.

Henk Holterman
Moderated +1, Funny.
greyfade
The MISRA C++ coding standard allows the use of goto to cover this exact kind of situation.
Richard Corden
+6  A: 

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.

Greg Hewgill
That's a C problem. With RIAA early return is not a problem as all the problems associated with early return are correctly handled.
Martin York
I understand that proper application of RIAA can solve the resource cleanup problem in C++, but I have seen the philosophical argument against early return continue in other environments and languages. One system I worked on where the coding standard prohibited early return had functions littered with boolean variables (with names like `continue_processing`) that controlled the execution of blocks of code further down in the function.
Greg Hewgill
What is RIAA? Is that anything like RAII? =D
Hooked
RIAA is a Resource Initialized by Antagonistic legal Actions. It's sort of like telling the free store to surrender memory to you because it has wronged you.
greyfade
er yes, s/RIAA/RAII/g; :)
Greg Hewgill
A: 

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++

ראובן
Yes on restructuring the loop, but big resounding no (and the consequent -1) on your other suggestions. Where warranted, this is a case for `goto`, must most definitely not exceptions, and, God forbid, `longjmp`. Both suggestions result in a significant performance hit for no good reason, and worse, make code much harder to read, and abuse the mechanisms for purpose that they were not indended for. "Exceptions are not a control flow mechanism" is very much true in C++ in general, and I've no idea how `longjmp` is superior to `goto` in this case, since it's essentially just nonlocal goto.
Pavel Minaev
+13  A: 
Greg Hewgill
+1: This is probably my favourite xkcd cartoon of all!
Richard Corden