Is it a bad practice to use break
statement inside a for
loop?
Say, I am searching for an value in an array. Compare inside a for loop and when value is found, break;
to exit the for loop.
Is this a bad practice? I have seen the alternative used: define a variable vFound
and set it to true when the value is found and check vFound
in the for
statement condition. But is it necessary to create a new variable just for this purpose?
I am asking in the context of a normal C or C++ for loop.
P.S: The MISRA coding guidelines advise against using break.
I don't see any reason why it would be a bad practice PROVIDED that you want to complete STOP processing at that point.
Lots of answers here, but I haven't seen this mentioned yet:
Most of the "dangers" associated with using
break
orcontinue
in a for loop are negated if you write tidy, easily-readable loops. If the body of your loop spans several screen lengths and has multiple nested sub-blocks, yes, you could easily forget that some code won't be executed after the break. If, however, the loop is short and to the point, the purpose of the break statement should be obvious.If a loop is getting too big, use one or more well-named function calls within the loop instead. The only real reason to avoid doing so is for processing bottlenecks.
Far from bad practice, Python (and other languages?) extended the
for
loop structure so part of it will only be executed if the loop doesn'tbreak
.Output:
Equivalent code without
break
and that handyelse
:I disagree!
Why would you ignore the built-in functionality of a for loop to make your own? You do not need to reinvent the wheel.
I think it makes more sense to have your checks at the top of your for loop like so
or if you need to process the row first
This way you can write a function to perform everything and make much cleaner code.
Or if your condition is complicated you can move that code out too!
"Professional Code" that is riddled with breaks doesn't really sound like professional code to me. It sounds like lazy coding ;)
No, break is the correct solution.
Adding a boolean variable makes the code harder to read and adds a potential source of errors.
I did some analysis on the codebase I'm currently working on (40,000 lines of JavaScript).
I found only 22
break
statements, of those:switch
statements (we only have 3 switch statements in total!).for
loops - a code that I immediately classified as to be refactored into separate functions and replaced withreturn
statement.break
insidewhile
loop... I rangit blame
to see who wrote this crap!So according to my statistics: If
break
is used outside ofswitch
, it is a code smell.I also searched for
continue
statements. Found none.