Breaking a "for" loop using "break" considered harmful?

José Tomás Tocino picture José Tomás Tocino · Jul 10, 2010 · Viewed 60.1k times · Source

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.

Answer

fire.eagle picture fire.eagle · Jul 10, 2010

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.