23

Some days ago I started a quick open source project and, when some mates looked at the code on svn, one of them told me that using break statement inside a for loop is considered harmful and shouldn't be done.

He added, though, that I would find several cases of break statements inside for loops on Linux kernel source code, but that was just because only Linus Torvalds and Chuck Norris were allowed to use it and no one else.

What do you think? I see no problem in using break inside a for loop. In my opinion, emulating the behaviour of break using boolean variables or something alike adds a lot of innecesary overhead and makes the code less straightforward.

Also, there's no room for comparison with goto, because break cannot arbitrarily change program's flow from one point to the other lie goto does.

kaybee99
  • 4,566
  • 2
  • 32
  • 42
José Tomás Tocino
  • 9,873
  • 5
  • 44
  • 78
  • I think `continue` is considered "harmful" though, in the same league as "goto" (both can be useful, but both can obscure code). `break` looks fine to me though, personally. – Johannes Schaub - litb Jul 10 '10 at 01:44
  • 2
    I use `break` very often, and `continue` quite often as well. I think that -- and the same things applies to multiple exists, Delphi `while` statements, etc., etc. -- that in most cases when someone says "don't use the X construct", then he/she is is not very used to writing complex algorithms and/or that he/she is not very experienced in the language at hand. Because, if one is very experienced at the language at hand, then one knows how to use this construct, and if one often writes complex algorithms, then one will love all these constructs. – Andreas Rejbrand Jul 10 '10 at 19:44
  • 6
    @BilltheLizard: The "Possible Duplicate" link is dead. – Christian Ammer Apr 01 '14 at 11:13

9 Answers9

45

I see no problem with using breaks. There will always be circumstances where you want to stop processing a loop, and using a break; makes much more sense (and makes it more readable!) than setting your loop counter up to a value that would make your loop stop at the next iteration.

fire.eagle
  • 2,723
  • 1
  • 21
  • 23
  • 8
    I see no proble with using goto. There will always be circumstances where you want to stop processing a very nested loop, and using goto; makes more sense (and makes it more readable!) than having boolean values to tell you when to get out of the loops. – Carlos Muñoz Jul 26 '10 at 13:36
41

Obligatory:

XKCD Goto

The point is that you should not avoid it purely on grounds of bad practice (or velociraptors), but consider on a case by case basis.

It's all about clarity. As you said, you never have to use it, but in some cases it promotes readability. It's useful when the loop usually terminates normally, but in rare cases you have to bail out. Loops that usually (or always) break are more of a code smell (but could still be appropriate).

Community
  • 1
  • 1
Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
  • 13
    +1 for providing a good answer with this comic. I recall seeing one heavily upvoted answer that was this comic and nothing else, ugh. – Maulrus Jul 10 '10 at 01:38
22

Not only is there no problem to using break, I'd say anyone saying it is "considered harmful" is downright wrong.

break is a language feature used to abort a loop - you could use goto, but then you incur the (appropriate) wrath of the XKCD comic below. You could use a flag in the condition, but that hampers readability. break is not only the easiest, but also the clearest way many times to bust out of a loop. Use it as it was meant to be used.


Edit: To get at a larger picture here: When you're writing code, the guiding principle to "should I use language feature X or Y" should be "which way will result in the more elegant code"? Elegance, in code, is pretty much an art, but I'd lay it down as a fine balance between readability and algorithmic (read: not micro-optimizations) efficiency. Readability is going to be determined by length, complexity of the code, etc. A one-line boost::bind may very well be harder to read & understand than a 3 line loop.

If a language feature can help you write code that is easier to understand while getting the job done, then use it. This applies to break, goto, C++ exceptions, etc. Don't follow a "X is (evil|considered harmful)" blindly - apply common sense and logic each time.

fredoverflow
  • 256,549
  • 94
  • 388
  • 662
Thanatos
  • 42,585
  • 14
  • 91
  • 146
12

Not only is there no problem with break, it's also OK to use goto when break is insufficient. Don't be afraid of multiple returns, either.

All of the above only applies if it makes the code easier to understand*.

*And if your PHB allows it...

Community
  • 1
  • 1
Cogwheel
  • 22,781
  • 4
  • 49
  • 67
8

I think your mate is insane. break is perfectly acceptable, perfectly readable, and perfectly maintainable. Period.

Scott Stafford
  • 43,764
  • 28
  • 129
  • 177
3

There is a paradigm that any loop should only have one point of exit (same as a function should only have one return). This has to do with readability. Too many exit points can make the code very difficult to understand. Also, it is important if you want to do code verification (i.e. mathematically proof if your code is correct).

However, guidelines are often there to help, but are not strict. There are possibly situations where a break is better than not using it. Hence, one should be pragmatic about this, but understand the reason for such principles in order to create good code.

txwikinger
  • 3,006
  • 1
  • 25
  • 33
1

I think it depends on context. While it may be 'bad' coding style in some situations, I can't think of a case where it would be harmful.

In fact, in some cases I would recommend it. For example, if you were using a linear search, any case (except the very worst case), a break would improve your speed. I think breaking out of the loop when you've found your needle would be perfectly acceptable, and it would be more readable than messing around with the loop variable (which might not solely be used for the loop, depending on your program) or wrapping the loop body in an if block. (And the other option, an if which contains continue, combines the worst of two worlds: wrapping loop logic in an if block, and the poor coding style railed against by people like your friends who don't like break.)

Brian S
  • 4,878
  • 4
  • 27
  • 46
  • You should not recommend break on performance grounds. Compilers can usually optimise status variables. – Artelius Jul 10 '10 at 01:33
  • Fair point. The point I was trying to make was if, for example, I'm performing a linear search on a large number of elements and I find what I'm looking for at index 2, I would much prefer to stop looking than continue looping over the remaining elements which I know I don't want. On the other hand, if I know I'll have a large number of elements, I probably wouldn't go for linear search, anyway. – Brian S Jul 10 '10 at 19:25
1

Incrementing your loop counter instead of using break also means you finish executing the current iteration of the loop, which may or may not be desirable.
Of course, you could wrap the rest of it in an if clause, and then do it again when you realize you need to check whether or not to stop looping multiple times, and you will quickly realize why people use break;

Larry Wang
  • 986
  • 6
  • 17
1

I suggest this algorithm if you're considering using a given technique.

  • If it is considered good practice:
    • use it.
  • If it is not considered good practice:
    • use it only if you judge it to be the best long-term solution.
  • If it is considered evil:
    • use it only if you judge it to be the best long-term solution and you are extremely confident in your judgement. Beware: things which are considered evil tend to be deceptively appealing.

I would classify break; as "not good practice". Use it when it makes the code more readable, reduces the chance of bugs, does not complicate debugging, etc.

Artelius
  • 48,337
  • 13
  • 89
  • 105