A break within two for actually works as a continue?

Asked

Viewed 2,438 times

5

If I happen to have one break within two for, as in the example below:

for(int i = 0; i < n; i++)
{
    for(int j = 0; j < m; j++)
    {
        break;
    }
{

The break won’t make the show come out of both for, only of for from within, correct?
So in this case, this break functions as a continue to the for containing the i, because it will skip the loop of for more internal?

I’ve had this doubt for a while, I’d like to be sure whether I can think this way or not.

1 answer

8


First, the difference between the break and the continue:

  • The continue jumps to the next cycle iteration. That is, just ignore the rest of the instruction block of an iteration.

  • The break forces the cycle to exit. That is, it does not skip just one iteration, but completely ends the cycle execution.

In this case, in the original language (English) it is very easy to understand what each of the instructions represents, just add the word loop:

  • break loop - breaks the loop/cycle.
  • continue loop - continues loop/loop (skips an iteration).

In your particular case, like break (unlabeled) only ends the execution of the cycle where it is inserted, will have the same practical effect as a continue in the outermost cycle, that is, it will only skip one iteration.

The break won’t make the show come out of both for, only of for from within, correct?

Yes, correct. But attention: This behaviour results from the fact that the second cycle is the only instruction in the outermost cycle. Imagine that whoever is keeping your code adds another instruction to your code. Something like this:

for(int i = 0; i < n; i++)
{
    for(int j = 0; j < m; j++)
    {
        break;
    }
    //executa novo procedimento
    MyObject.funcaoMaravilha();
}

In this case the break will not have the same effect as the execution flow continues in the instruction MyObject.funcaoMaravilha(); and the break It will no longer function as a continue to the for containing the i.

Finally, and although the question explicitly refers to the C language, here is a small tip for those who use Java. Java allows the use of "named/labeled"

first:
for (int i = 0; i < 10; i++) {
    second:
    for (int j = 0; j < 5; j++) {
        break first;
    }
}
MyObject.fazCoisas();

In this case the break will end the execution of the instruction associated with the tag first. Execution flow continues in instruction MyObject.fazCoisas(); To achieve the same effect in the C language, you would need something like goto.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.