0
0
CppHow-ToBeginner · 3 min read

How to Use Continue in C++: Syntax and Examples

In C++, the continue statement is used inside loops to skip the rest of the current iteration and immediately start the next iteration. It works with for, while, and do-while loops to control flow efficiently.
📐

Syntax

The continue statement is used inside loop bodies to skip the remaining code in the current iteration and jump to the next iteration.

  • for loop: moves to the update expression and then checks the condition again.
  • while/do-while loop: jumps directly to the condition check.
cpp
for (initialization; condition; update) {
    if (some_condition) {
        continue; // skip rest and go to next iteration
    }
    // other code
}
💻

Example

This example prints numbers from 1 to 10 but skips printing even numbers using continue. When the number is even, continue skips the print statement and moves to the next number.

cpp
#include <iostream>

int main() {
    for (int i = 1; i <= 10; i++) {
        if (i % 2 == 0) {
            continue; // skip even numbers
        }
        std::cout << i << " ";
    }
    return 0;
}
Output
1 3 5 7 9
⚠️

Common Pitfalls

One common mistake is using continue outside of loops, which causes a compilation error. Another is misunderstanding that continue skips only the current iteration, not the entire loop.

Also, placing continue before important code inside the loop can unintentionally skip necessary operations.

cpp
#include <iostream>

int main() {
    int i = 0;
    // Wrong: continue outside loop causes error
    // continue;

    for (int j = 0; j < 5; j++) {
        if (j == 2) {
            continue; // skips printing 2
        }
        std::cout << j << " ";
    }
    return 0;
}
Output
0 1 3 4
📊

Quick Reference

Tips for using continue in C++ loops:

  • Use continue to skip the rest of the current loop iteration.
  • Works with for, while, and do-while loops.
  • Do not use continue outside loops; it causes errors.
  • Helps simplify conditions by avoiding nested if statements.

Key Takeaways

Use continue inside loops to skip the current iteration and proceed to the next.
continue works with all loop types: for, while, and do-while.
Never use continue outside of loops; it causes compilation errors.
Placing continue carefully avoids skipping important code unintentionally.
continue helps make loop code cleaner by reducing nested conditions.