When coding, why is exiting a loop using break; bad?

  • Thread starter Thread starter r.meghdies
  • Start date Start date
  • Tags Tags
    Break Coding Loop
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
1 reply · 3K views
r.meghdies
When coding, why is exiting a loop using"break;" bad?

when coding, to exit a loop i was told using "break;" (in java) is really bad...why!
 
Physics news on Phys.org
It makes the code hard to follow. If the exit criteria is at the top of the loop, it is easy for the reader to figure out what is happening. However a break buried deep in a loop can do something surprising and surprises make code very difficult to follow. Then there are labeled breaks which act somewhat the same as a goto in C (more or less) and can quickly turn your code into an unreadable mess.

Breaks are always ok in switch statements. But elsewhere USE CAUTION!

Remember any significant chunk of code will be maintained by someone else and that someone will want easy to read code not one riddled with hidden break statements.
 
Last edited: