# Continue and break

The continue and break statements can be used within loops to interrupt their normal execution flow. I’s usually not very difficult to replace these statements when used within loops by other statements, such as if statements. Thus, if you prefer, you do not have to use continue and break statements within loops, though one should be aware of them (to be able to understand code from other programmers) and they might make some loops simpler.

### Continue statement

The continue-statement stops the current iteration of the nearest enclosing loop and immediatly starts the next loop iteration. For instance, the while-loop below reads a list of integers given by the user and computes the sum of square-root of each non-negative input value. Note that in the body of the loop, the if-statement (line $6$) tests whether the value read is negative. If that is the case then the next iteration of the loop is started by reading the next value from std::cin (line $5$). If the test (value < 0) (line $6$) returns false then the statement in line $10$ in the loop’s body is executed, before getting to the next iteration of the loop.

It is possible to re-write the code presented above without using the continue statement in the loop’s body, as shown next.

The else part if-statement (lines $8$ to $10$) is not really need, though it makes it clear in the code that nothing in the body of the loop is executed when value is negative.

Let us see one more simple example, this time with a for-loop. The body of the loop below tests if i is even (line $2$) and, if so, then the continue-statement forces execution to proceed immediatly with the next iteration, i.e. i is incremented and then the test i < 100 is performed.

### Break statement

Note that in this section, we discuss the use of break-statements in the body of a loop. break-statements can also be used in a switch-statement, though this section does not address this case.

The break-statement terminates the nearest enclosing loop and execution proceeds at the statement immediatly following the terminated loop. Consider the figure below illustrating two nested loops. When the break-statement in the body of loop2 is executed then loop2 terminates and the program continues its excution at the statement in the body of loop1 immediatetly following loop2.

We show below a concrete example of a while-loop that reads a list of integers given by the user until the first negative integer entered. Each value read is then displayed, one per line. In this case, no value is considered after the first negative integer in the input. Thus, if the user enters the list of values 2 4 6 8 12 -99 1 1 1 1 then all integers after $-99$ are not read.

Note that the while-loop of the program above can be re-written without the use of a break-statement.