First, the difference between break
and continue
:
-
The continue
jumps to the next cycle iteration. That is, it just ignores the rest of the instruction block from an iteration.
-
The break
forces the output of the cycle. That is, it does not skip just one iteration, but it completely terminates the cycle execution.
In this case, in the original language it is very easy to see what each of the instructions represents, just add the word loop :
-
break loop - break the loop / cycle.
-
continue loop - continues the loop / cycle (jumps an iteration).
In your particular case, as break
(unlabeled) only completes the execution of the cycle where it is inserted, it will have the same practical effect as a continue
in the outermost cycle, ie it will only skip an iteration .
The break
will not cause the program to exit the two for
, only the for
from inside, correct?
Yes, right. But attention: This behavior 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 in 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 because the execution stream continues in the MyObject.funcaoMaravilha();
statement and the break
will no longer function as a continue
to for
containing i
.
To finish and even if 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 finish executing the statement associated with tag first . The execution flow continues in the MyObject.fazCoisas();
statement. To achieve the same effect in the C language, you would need something like goto
.