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.
Using break as well as continue in a for loop is perfectly fine. It simplifies the code and improves its readability.
break terminates the execution of a for or while loop. Statements in the loop after the break statement do not execute. In nested loops, break exits only from the loop in which it occurs. Control passes to the statement that follows the end of that loop.
The purpose the break statement is to break out of a loop early. For example if the following code asks a use input a integer number x. If x is divisible by 5, the break statement is executed and this causes the exit from the loop.
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.
Obligatory:
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With