Page 1 of 1

[HD Pg 174, Sec. 7.7.2 - rules-for-labeled-break-and-continue]

Posted: Thu Jul 22, 2021 5:37 am
by enthunoob
What confuses me is that if there are two loops within each other and inside the inner loop a continue or break statement with the name of the outer loop is called, then it jumps to the outer loop label and it still remembers the iteration values of the inner loop.

I would expect that jumping to the (label of the) code above, it just starts executing code from there and when it reaches the inner loop (again) it just starts with the initialization part of that inner loop. But it doesn't.

public static void doIt(int h){ int x = 1;
LOOP1 : do{
//when execution comes here from jumping to the LOOP1 label below (fe with input values h=5 and iteration values x =3 and y=4) when it goes to the next line of code, y is not reinitialized to 1 because the initialization part of the inner loop is (somehow) skipped.
LOOP2 : for(int y = 1; y < h; y++ ) {
if( y == x ) continue;
if( x*x + y*y == h*h){ System.out.println("Found "+x+" "+y);
break LOOP1;
} } x++;
}while(x<h);
}

What I learned in this chapter is that a label always marks a block of code. So 'local variables' of a labeled block of code, such as iteration values, are stored/memorized as long as that block did not finish completely. Just like local methods are kept in memory as long as that method did not finish entirely.


Please let me know if I understand correctly. And if so, I think it would be worth mentioning in this chapter.

Re: [HD Pg 174, Sec. 7.7.2 - rules-for-labeled-break-and-continue]

Posted: Thu Jul 22, 2021 5:53 am
by admin
>What confuses me is that if there are two loops within each other and inside the inner loop a continue or break statement with the name of the outer loop is called, then it jumps to the outer loop label and it still remembers the iteration values of the inner loop.

No, it doesn't.

>I would expect that jumping to the (label of the) code above, it just starts executing code from there and when it reaches the inner loop (again) it just starts with the initialization part of that inner loop. But it doesn't.

That is exactly what it does.

You are doing something wrong.

Re: [HD Pg 174, Sec. 7.7.2 - rules-for-labeled-break-and-continue]

Posted: Thu Jul 22, 2021 4:47 pm
by enthunoob
Thanks, I was.