Page 1 of 1

Question about com.enthuware.jfcja.v8.2.292

Posted: Wed Jul 19, 2023 7:04 pm
by james82abn
For a nested loop with a break in its innermost loop, I am confused about the initialization. From the answer to this question and answer, it appears that the innermost loops (j, k) re-initialize to zero rather than maintain the iteration it had prior to the break. Is there a source where this situation (why the inner loops are re-initialized after a break) is explained.

Code: Select all

class LoopTest
{
	public static void main(String [] args)
	{
		int counter = 0;
		outer: for(int i = 0; i < 3; i++) 
			    for(int j = 0; j < 3; j++)
				for(int k = 0; k < 3; k++)
				{
					if(k - j > 0) break middle;
					counter++;
				}
		System.out.println(counter);
	}
}

Re: Question about com.enthuware.jfcja.v8.2.292

Posted: Thu Jul 20, 2023 10:23 am
by admin
Well, a break statement "breaks" the loop. Meaning, the loop condition and the increment section of the for loop are not executed and the control is transferred immediately to the statement that appears immediately after the closing brace of the for loop. Everything regarding the loop (i.e. the loop variable etc.) is forgotten. In other words, this loop goes out of scope. This is the general concept behind the break statement.

Now, if the for loop is nested inside another loop, then the next statement after the loop is the remaining code of the outer loop. Thus, the iteration of the outer loop will continue and if the next iteration of the outer loop is executed, then the inner loop will also be executed afresh. Therefore, the loop variables of the inner loop will be reinitialized. There is no knowledge of the previous execution of the inner loop.

I am not sure what kind of reason are you looking for but this is how loops have been designed to work. Code inside a loop is executed afresh upon each iteration.