cometta
cometta

Reputation: 35689

iterator for loops with break

let say my code look like below

for(..)
  for(..)
    for(..){
            break;  //this will break out from the most inner loop OR all 3 iterated loops?
    }

Upvotes: 6

Views: 16152

Answers (8)

Adriaan Koster
Adriaan Koster

Reputation: 16209

Many people here don't like labels and breaking. This technique can be compared to using a 'goto' statement, a flow control statement which allows jumping out of a block of code in a non-standard way, obliviating use of pre- and post conditions. Edsger Dijkstra published a famous article in Communications of the ACM, march 1968, 'Goto statement considered harmful' (it's a short read).

Using the same reasoning presented in the article, returning from inside an iteration as suggested by TimW is also bad practice. If one is strict, to create readable code, with predictable entry- and exit points, one should initialize the variable which will hold the return value (if any) at the beginning of the method and return only at the end of a mehod.

This poses a challenge when using an iteration to perform a lookup. To avoid using break or return one inevitably ends up with a while-loop with a regular stop condition and some boolean variable to indicate that the lookup has succeeded:

boolean targetFound = false;
int i = 0;
while (i < values.size() && ! targetFound ) {

    if (values.get(i).equals(targetValue)) {   
        targetFound  = true;
    }
}
if (!targetFound) {
    // handle lookup failure
} 

Ok, this works, but it seems a bit clunky to me. First of all I have to introduce a boolean to detect lookup success. Secondly I have to explicitly check targetFound after the loop to handle lookup failure.

I sometimes use this solution, which I think is more concise and readable:

lookup: {

    for(Value value : values) {

        if (value.equals(targetValue)) {   
            break lookup;  
        }
    }
    // handle lookup failure here
}

I think breaking (no pun intended) the rule here results in better code.

Upvotes: 0

Dimitri
Dimitri

Reputation: 165

as often mentioned i don't like to break with a label eather. so while in a for loop most of the time i'm adding a boolean varible to simple exit the loop.. (only if i want to break it of cause;))

boolean exit = false;
for (int i = 0; i < 10 && !exit; i++) {
   for (int j = 0; j < 10 && !exit; j++) {
      exit = true;
   }
}

this is in my opinion more elegant than a break..

Upvotes: 1

TimW
TimW

Reputation: 8447

Yes, without labels it will break only the most inner loop.
Instead of using labels you can put your loops in a seperated function and return from the function.

class Loop {
    public void loopForXx() {
        untilXx();
    }

    private void untilXx() {
        for()
            for()
                for()
                    if(xx)
                        return; 
    }
}

Upvotes: 4

ufukgun
ufukgun

Reputation: 7209

it will breake from most inner loop,

if you want to break from all, you can hold a variable and change its value when you want to break, then control it at the beginning of each for loop

Upvotes: -2

Otto Allmendinger
Otto Allmendinger

Reputation: 28268

This will only break out from the inner loop. You can also define a scope to break out from. More from the language specs:

A break statement with no label attempts to transfer control to the innermost enclosing switch, while, do, or for statement of the immediately enclosing method or initializer block; this statement, which is called the break target, then immediately completes normally.

Upvotes: 11

Greg Hewgill
Greg Hewgill

Reputation: 993273

Your example will break out of the innermost loop only. However, using a labeled break statement, you can do this:

outer:
  for(..)
    for(..)
      for(..){
        break outer;  //this will break out from all three loops
      }

Upvotes: 29

Konamiman
Konamiman

Reputation: 50273

You should take a look here: http://java.sun.com/docs/books/tutorial/java/nutsandbolts/branch.html

Upvotes: 3

Toms
Toms

Reputation: 76

From the most inner loop :)

    int i,j,k;
    for(i = 0; i < 2; i++)
            for(j = 0; j < 2; j++)
                    for(k = 0; k < 2; k++)
                    {
                            printf("%d %d %d\n", i, j, k);
                            break;
                    }

Will produce :

0 0 0
0 1 0
1 0 0
1 1 0

Upvotes: 3

Related Questions