1

Follow up to this page: Breaking out of nested loops in Java

This code works just fine (part of a Sudoku solver, so p is a 9x9 table):

int r = 0, c = 0;
out:
for(r = 0; r < 9; ++r){
  for (c = 0; c < 9; ++c){
    if (p[r][c] == 0){
      break out;
    }
  }
}
// do stuff with r, c

But this code fails! The only change is that the 'init' sections of the for loops are empty.

int r = 0, c = 0;
out:
for( ; r < 9; ++r){
  for ( ; c < 9; ++c){
    if (p[r][c] == 0){
      break out;
    }
  }
}
// processes first row of array as it should, then breaks out with r=9, c=9

Since r and c are defined and initialized above the loops, these blocks ought to do exactly the same thing, but they don't. Anyone have any idea why this behaves the way it does?

Community
  • 1
  • 1
  • 1
    your inner loop is executed for only one round of outer loop. then it never meets the evaluation c<9 afterwards. You probably need to look at "scope of variables" in java and its impact. – Jimmy Sep 18 '14 at 14:32

1 Answers1

3

Yes, the problem is the second loop requires c to be reset to 0 or it will only run through for the first iteration of the outer loop. The second time through (e.g. when r = 1) c will already be 9 and the loop body will not be entered. So, you need

for (c = 0 ; c < 9; ++c){

or,

for( ; r < 9; ++r){
  c = 0;
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249