CPP Tutorial



BREAK CONTINUE & GOTO


Break, Continue, and Goto in C++

These are control statements that allow you to alter the normal flow of loops or program execution.


1. The break Statement

The break statement is used to exit from the nearest enclosing loop or switch statement immediately. It stops the loop even if the loop condition is still true.

Example:

#include <iostream>
using namespace std;

int main() {
    for (int i = 1; i <= 10; i++) {
        if (i == 5) {
            break;  // Exit loop when i is 5
        }
        cout << i << " ";
    }
    return 0;
}
  

Output: 1 2 3 4
The loop stops when i becomes 5 because of the break statement.


2. The continue Statement

The continue statement skips the current iteration of the loop and proceeds with the next iteration.

Example:

#include <iostream>
using namespace std;

int main() {
    for (int i = 1; i <= 5; i++) {
        if (i == 3) {
            continue;  // Skip when i is 3
        }
        cout << i << " ";
    }
    return 0;
}
  

Output: 1 2 4 5
The loop skips printing 3 because of continue.


3. The goto Statement

The goto statement transfers control unconditionally to a labeled statement within the same function. It is generally discouraged because it can make code harder to read and maintain, but can be useful in some scenarios.

Syntax:

goto label;

...

label:
    // code to execute
  

Example:

#include <iostream>
using namespace std;

int main() {
    int num = 1;

    start:  // label
    cout << "Number: " << num << endl;
    num++;

    if (num <= 5) {
        goto start;  // jump to label
    }

    return 0;
}
  

Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5


Summary

Statement Effect Usage
break Exits the current loop or switch immediately. Stop loop early based on condition.
continue Skips current loop iteration and moves to next. Skip processing certain values.
goto Jumps to a labeled statement unconditionally. Rare use cases; generally avoided for readability.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review