What is the continue statement in C++?
Overview
The continue statement in C++ is used to stop an iteration that is running and continue with the next one.
How does it work?
The continue statement works in such a way that it cancels every statement running in the iteration of a loop and moves the control back to the top of the loop. In other words, it continues to the next iteration when a certain condition is reached.
In C++, we can use the continue statement in the while and for loops.
Using the continue statement in a for loop
In the example below, we will use the continue statement in a for loop to continue to the next iteration when the value of x equals 5.
Code example
#include <iostream>using namespace std;int main() {for (int x = 0; x < 10; x++) {if (x == 5) {continue;}cout << x << "\n";}return 0;}
Code explanation
-
Line 3: We use the
continuestatement to continue to the next iteration after the number'5'character in the range of values we created. -
Line 5: We start a
forloop and give an expression that makesxbe in the range of0to9. -
Line 6: We create a condition that states that if the value of
xis equal to5in the iteration, the iteration should stop at that point and continue to the next iteration6, using the continue statement. -
Line 9: We print the statement or command to execute provided the condition provided is true.
Using the continue statement in a while loop
In the code below, we will use the continue statement in a while loop to continue to the next iteration when x equals 5.
Code example
#include <iostream>using namespace std;int main() {int x = 0;while (x < 10) {if (x == 5) {x++;continue;}cout << x << "\n";x++;}return 0;}
Code explanation
- Line 5: We create an integer variable
xand assign it to0. - Line 6: Using the
whileloop, we make the values ofxto be less than10. - Lines 7, 8, and 9: Using the
ifstatement in line 7, we create a condition that ifxequals5, and the value ofxincrementing by1in line 8, the iteration should stop at that point and continue to the next value ofx, which is6using thecontinuestatement in line 9. - Line 11: We print all the values of
xproviding the condition provided in line 7 is true. - Line 12: We increment
xby1.