Go into the c language to explain the difference between continue and break

  • 2020-04-01 23:32:10
  • OfStack

People who think that C language is still a beginner, it seems that they still overestimate their own.

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =


#include <stdio.h> 
int main(void) 
{ 
   int flag=0; 
   for(int j=0; j <2; j++) { 
      if(j==0) { 
         switch(j) { 
            case 0: 
            continue; 
         } 
         flag=1; 
      } 
   } 
   printf( " flag:%dn ",flag); 
}

Output:
Flag: 0

If the code is:
Case 0: break;
Output:
Flag: 1.

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

Then look at:


#include <stdio.h> 
void main() 
{ 
   int flag = 0; 
   int j = 0 ; 
   for(j=0; j <2; j++) { 
      if(j==0) { 
         if(j==0) { 
            continue; 
         } 
         flag=1; 
      } 
   } 
   printf( " flag:%dn ",flag); 
}

Output:
Flag: 0

If the code is:
Break;
Output:
Flag: 0

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

In the C book, continue and break are described as follows:

The break statement can exit from the innermost loop or the switch statement.

The continue statement can only appear in for, while, and do loops

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

Conclusion: Continue is only valid for the loop body that contains it directly (i.e., for,while, and not in the switch{}); What breaks is the for,while, and switch block that contains it directly.


For example, if a break or continue appears in code that does not contain switch, then break breaks out of the loop body, and continue breaks out of the loop.

For code that nested switch statements in the loop,break only pops out of the innermost block, which if it were a switch, just pops out of the switch.

However, even if continue appears in the switch block, it will not work because the scope of continue is only for loop statements such as for while, so it will still break out of this loop.

If you don't pay attention to it, you will think that it is also jumping out of the switch block.


Related articles: