How to stop the inner and outer loop using the break statement

I have really simple code where I use breakinside the inner loop:

for (int it=0; it<5; it++) {
    for (int it2=0; it2<5; it2++) {
        if (it2==2) 
            break; //break here not it2, but it loop
        NSLog(@"it=%d it2=%d", it, it2);
    }
}

I get the output:

it=0 it2=0, it=0 it2=1, 
it=1 it2=0, it=1 it2=1, 
it=2 it2=0, it=2 it2=1,
it=3 it2=0, it=3 it2=1,
it=4 it2=0, it=4 it2=1

I know that in some programming languages ​​it is possible to determine which cycle operator should influence. Is it possible to call breakto stop the outer loop ( forwith a variable it)?

+4
source share
6 answers

If you really want to do this, then bite the bullet and use goto.

for (int it=0; it<5; it++) {
    for (int it2=0; it2<5; it2++) {
        if (it2==2) 
            goto end_outer_loop;
        NSLog(@"it=%d it2=%d", it, it2);
    }
}

end_outer_loop:

// more stuff here.

goto ( ). break - "" goto, C - , goto .

, , , return.. , goto, , .

+10

bool flag , :

bool flag = false;
for (int it=0; it<5; it++) {
    for (int it2=0; it2<5; it2++) {
        if (it2==2) { flag=true; break; }
        NSLog(@"it=%d it2=%d", it, it2);
    }
    if(flag) {break;}
}

, return, . return . .

goto , goto , , !

+4

C/++ - . , , goto - . goto , (IMO).

.

  • , . , break - , . , , , .

  • , , if() , " ", , . , , , if() ( ), , .

, .

+1

, return .

0

goto . goto .

,

int loop(int it,int it2)
{
  for (int it=0; it<5; it++) {
    for (int it2=0; it2<5; it2++) {
        if (it2==2) return 0; //function returns here
        NSLog(@"it=%d it2=%d", it, it2);
    }
  }
  return 1;
}
0

, ++ . , , goto. :

  • return

  • bool stopFlag = false; for (int it = 0; it <5 &! stopFlag; it ++) {for (int it2 = 0; it2 <5; it2 ++) {if (anything) {stopFlag = TRUE; break; }}

-1
source

Source: https://habr.com/ru/post/1535740/


All Articles