0

I am just curious as I have been using break statements a lot, but apparently I was told that is bad practice. Obviously logically if something is met it could terminate as well. I just want to know if there is something else besides break.

joe smith
  • 29
  • 1
  • 1
  • 5
  • 1
    exact dup of http://stackoverflow.com/questions/3922599/is-it-a-bad-practice-to-use-break-in-a-for-loop. check google before you post a question – Andy Guibert Nov 07 '15 at 02:40
  • 4
    Yes. Add a logical and to the loop [*condition*](https://en.wikipedia.org/wiki/For_loop#Traditional_for-loops). But I would disagree, and say that `break` is ***not*** a **universally** bad practice. – Elliott Frisch Nov 07 '15 at 02:40

3 Answers3

0

That would break out of the for loop. In fact break only makes sense when talking about loops, since they break from the loop entirely, while continue only goes to the next iteration try this:

for(int i= 0; i<MAX; i++){
if(listEmpt[i] == null){
    listEmpt[i] = employeeObj;
    i=MAX;
}

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

you can also use labeled breaks that can break out of outer loops (and arbitrary code blocks)

looplbl: for(int i=;i<;i++){

if (i == temp)
    // do something
else {
    temp = i;
    break looplbl;
}

}

An unlabelled break only breaks out of the enclosing switch, for, while or do-while construct. It does not take if statements into account.

See for more details.

Community
  • 1
  • 1
sirmagid
  • 1,090
  • 1
  • 16
  • 23
0

With regards about the use of break, you could check here.

Since while loops were not covered (another form of looping which I personally use a lot), you could look towards settings conditions for the loops such as

boolean flag = true;
while (flag) {
    //do something that modifies the below condition
    if (condition) {
        //do something
        flag = false;
    }
}

Upon which the loop will terminate when the condition equates to true, since that sets the flag to false.

Aaa
  • 134
  • 1
  • 8
-1

If you simply return from within your loop, that should be sufficient. Most people think you have to terminate the loop, but this is not the case.

Also, see this answer too.

Community
  • 1
  • 1
cavalleydude
  • 149
  • 1
  • 5