What is the priority for nested case, for and if loop?

I have a program like this:

switch(x) { case 1: for(i=0; i<10; i++) { if ((i==3) || (i==4) || (i==5) || (i==6) || (i==7)) { if (foobar[i]) break; // i am talking about this break } } ...further program break; /not this break 

If foobar[i] true, will the program exit the case label or for loop?

+4
source share
7 answers

For loop.

See: break Statement (C ++) :

The break statement completes the closest loop or conditional expression in which it is displayed . Control passes to which follows the completed expression, if any.

+5
source

break follows the type of the LIFO type, i.e. the last break will exit the first management structure. This way, the break you chose will exit the for loop, not the case .

+12
source

break will only exit the for loop. If you have nested statements, they will go only one level

+2
source

Is a for loop. The gap will bubble until it finds the first option, while either switch. Therefore, you can simply write your program as follows:

 switch(x){ case 1: int loopBreaked = 0; //If you want to know if the loop has breaked for(int i=0; i<10; i++) { if (i <= 7 && i >= 3 && foorbar[i]) { loopBreaked = 1; break; //breaks the loop } } break; //breaks the switch } 
+1
source

What about:

 for(i=3; i<=7 && !foobar[i]; i++) {} 
0
source

For completeness, break will break out of the innermost statement like for do while or switch . There is no need to exit the if , as simply completing a block of code will do the same job.

0
source

Your break breaks the for loop. And the break you use later break the switch . You can consider this code example:

 for(int i=0;i<len;i++) { for(int j=0;j<len;j++) { //statements break; } //statements break; } 

break inside the inner loop breaks the inner loop, and the next break statement break the outer loop. In your sample code, the break you noticed is inside a for loop. Thus, the for loop will break.

0
source

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


All Articles