Introduction to C++ | continue Statement

C++ continue Statement

The continue statement in C++ is used to skip the current iteration of a loop and proceed with the next iteration. It does not terminate the loop like break, but rather allows the loop to continue from the next iteration, skipping the remaining code for the current iteration.

What is the continue Statement?

The continue statement is used to skip over specific portions of a loop's body based on a condition. When the continue statement is encountered, it immediately jumps to the next iteration of the loop. This is useful when you want to skip over certain iterations without terminating the entire loop.

Syntax of the continue Statement

The syntax for the continue statement is as follows:

Syntax of continue


        continue;
                    

Example of continue in Loops

Here is an example of how the continue statement can be used inside a loop to skip over certain iterations:

Code Example


        #include <iostream>
        using namespace std;
        
        int main() {
            for (int i = 1; i <= 10; i++) {
                if (i == 5) {
                    continue;  // Skip the iteration when i equals 5
                }
                cout << "i = " << i << endl;
            }
        
            return 0;
        }
                    

Output

i = 1
i = 2
i = 3
i = 4
i = 6
i = 7
i = 8
i = 9
i = 10

Example of continue in while Loop

The continue statement can also be used in a while loop. It skips the rest of the current iteration and moves to the next one.

Here’s an example of using continue in a while loop:

Code Example: continue in while Loop


        #include <iostream>
        using namespace std;
        
        int main() {
            int i = 1;
            while (i <= 10) {
                if (i == 5) {
                    i++;  // Skip the rest of the code when i equals 5
                    continue;
                }
                cout << "i = " << i << endl;
                i++;
            }
        
            return 0;
        }
                    

Output

i = 1
i = 2
i = 3
i = 4
i = 6
i = 7
i = 8
i = 9
i = 10

When to Use continue

Use the continue statement when you want to skip the current iteration of a loop based on a specific condition. It is especially useful when certain conditions don't require further processing in the current loop iteration, but you still want the loop to continue.

Pro Tip:

💡 Pro Tip

Although the continue statement can be handy, it is best used sparingly. If your loop logic becomes too complex with multiple continue statements, it may be a sign that you should refactor the loop or the condition that triggers the skip.