Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Breaking a "for" loop using "break" considered harmful? [duplicate]

Tags:

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.

like image 952
José Tomás Tocino Avatar asked Jul 10 '10 01:07

José Tomás Tocino


People also ask

Is using break in a loop bad?

Using break as well as continue in a for loop is perfectly fine. It simplifies the code and improves its readability.

What happens when you break a for loop?

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.

Why break is used in for 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.


2 Answers

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.

like image 124
fire.eagle Avatar answered Sep 27 '22 16:09

fire.eagle


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).

like image 36
3 revs Avatar answered Sep 27 '22 16:09

3 revs