Question

for (...)
    for (...)
    {
        break;
        break;   // 1
    }

Will the code at (1) execute? There could also be there continue or anything else. I know I could just check in my debugger but I wanna know what C++ standard says about it as my compiler might just be a special case.

Was it helpful?

Solution

As per the specifications

6.6.1 The break statement [stmt.break]

The break statement shall occur only in an iteration-statement or a switch statement and causes termination of the smallest enclosing iteration-statement or switch statement; control passes to the statement following the terminated statement, if any.

Hence 1 should not even reach . Some Java compiler might even flag that code unreachable.

OTHER TIPS

As per standard

Within nested statements, the break statement ends the do, for, switch, or while statement that immediately encloses it.

So in your case it will always break at first and never come to second break statement.

The code at(1) will not be executed, break means jump out of the loop, so after the first break, the code will jump out of the inner loop.

Within that particular loop, no, no code after break will execute as break will drop out of that loop and continue execution from after the end of the inner for loop. Although any code outside of the inner loop that appears after the break (within the outer loop), will be executed.

No, each time the first break statement is hit the inner loop will exit and the second break statement will never be reached.

You can see here.

And I am sure the next break never exce . No matter what compiler you use.

No. The code execution jumps out of the inner first loop the moment a break is encountered.
Even if the code is this way

break;
continue;
break;

the same thing happens. Continue is just a way to tell the compiler to iterate the loop further skipping any code in between.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top