In this video, we'll look at the continue and break statements in c++.
The continue and break statements can be used within all of c++ loop
constructs to provide more explicit control over the loopy behavior.
Their behavior is really easy to understand.
When a continue statement is executed in the loop, no further
statements in the body of the loop or executed and control immediately
goes directly to the beginning of the loop for the next iteration.
So you can think of this as skip processing in the rest
of this iteration and go to the beginning of the loop.
In the case of the while loop and the for loop, the condition
will immediately be tested again.
When the brake statement is executed in the loop, no further
statements in the body are executed and the loop is terminated.
So controllers transfer to the statement immediately
following the loop.
Let's see an example that uses both the continue and break statements.
In this example, we have a vector of integers.
Let's assume that this data comes from some sort of device and
occasionally we get noise in the data.
The noise is represented by the -1.
We really don't want to process the noise.
We want to ignore it.
We also need to stop processing when we get to stop signal
which is represented by -99.
In this case, we can use the range-based for loop to iterate
over all the vector elements.
At each iteration, we can check if the value is -99
in which case we are done.
We could set of flag to done and handle the done Boolean in the loop
condition as we've done before or we can simply breakout of the loop.
In this case, we're using the break statement to break
out of the loop completely.
In the else if statement, we know we haven't seen a negative 99.
So we can check from -1, that represents noise.
If we see it, we can continue.
This stops the iteration and control goes back to the beginning of the
loop in a new iteration begins.
Finally if we hit the l statement, we know we don't have a -99
and we know we don't have a -1, so we process that data.
In this case, we'll just display it.
In this example, we display 1 2 3.
Continue and break statements are very, very easy to use.
However, don't overuse them.
I'm obviously exaggerating here.
But if you have a loop that has 10 brakes and 12 continues in its
body, that's a very complex piece of code to try to understand.
The less ways that you can come into a loop and out of the loop, the
better we can understand and debug it.
We'll see the brake statement again again when we talk about
infinite loops in the next video.