![]() Ndim's answer observes that some people may avoid breaks to maintain a relatively consistent loop run-time, but you were comparing break against use of a boolean early-exit control variable where that doesn't holdĮvery now and then people observing such bugs realise they can be prevented/mitigated by this "no breaks" rule. Someone may change the conditional test in the for statement without noticing that there are other delocalised exit conditions Sometimes this causes bugs, for example:Ī resource acquired at the top of the block may be released at the bottom (this is true even for blocks inside for loops), but that release step may be accidentally skipped when a "premature" exit is caused by a break statement (in "modern" C++, "RAII" is used to handle this in a reliable and exception-safe way: basically, object destructors free resources reliably no matter how a scope is exited) when you use break, you skip the rest of the code in the block, and the remaining iterations. The obvious consequential question is why would anyone recommend otherwise? Well. I agree with others who recommend using break. Using something like a Set or Map may provide better results. If you're considering using a break while iterating over a sequence for some particular item, you might want to reconsider the data structure used to hold your data. I will say that break (and return) statements often increase cyclomatic complexity which makes it harder to prove code is doing the correct thing in all cases. To improve readability many languages ( at least Java does) support breaking to labels which will greatly improve readability. There is nothing inherently wrong with using a break statement but nested loops can get confusing.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |