Skillversitas

Jump Statements in C++

Jump statements are instructions that control the program's execution flow by "jumping" to another location in the code. C++ provides four main jump statements: break, continue, goto, and return. Each statement has specific uses and usage rules.

Jump statements are very important for controlling program flow, especially in loops and functions. However, improper use — especially of goto — can make code hard to read and maintain. Therefore, a solid understanding of when and how to use each jump statement is essential.

Types of Jump Statements

1. Break

break stops the execution of a loop or switch statement and continues with the statement following that loop/switch.

for (int i = 0; i < 10; i++) {
    if (i == 5) break;  // Stop when i == 5
    cout << i << " ";
}
// Output: 0 1 2 3 4

2. Continue

continue skips the rest of the current iteration and moves on to the next iteration in the loop.

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

3. Return

return returns a value from a function and stops the execution of that function.

int add(int a, int b) {
    return a + b;
}

4. Goto

goto jumps to a specified label within the same function. Its use should be cautious because it can make code hard to understand.

goto label;
// ... other code ...
label:
// code after the label

Code Example

#include <iostream>
#include <string>
using namespace std;

// Function to demonstrate return
int findValue(int arr[], int size, int target) {
    for (int i = 0; i < size; i++) {
        if (arr[i] == target) {
            return i;  // Return the index if found
        }
    }
    return -1;  // Return -1 if not found
}

// Function to check for prime numbers
bool isPrime(int n) {
    if (n <= 1) return false;
    if (n <= 3) return true;
    if (n % 2 == 0 || n % 3 == 0) return false;
    for (int i = 5; i * i <= n; i += 6) {
        if (n % i == 0 || n % (i + 2) == 0)
            return false;
    }
    return true;
}

int main() {
    // Break in a for loop
    cout << "=== Break in a For Loop ===" << endl;
    for (int i = 1; i <= 10; i++) {
        if (i == 7) {
            cout << "\nFound 7, stopping!" << endl;
            break;
        }
        cout << i << " ";
    }
    cout << endl;

    // Break in a while loop
    cout << "\n=== Break in a While Loop ===" << endl;
    int number;
    int total = 0;
    while (true) {
        cout << "Enter a number (negative to stop): ";
        cin >> number;
        if (number < 0) break;
        total += number;
    }
    cout << "Total: " << total << endl;

    // Continue - skip even numbers
    cout << "\n=== Continue (Skip Even) ===" << endl;
    for (int i = 1; i <= 15; i++) {
        if (i % 2 == 0) continue;
        cout << i << " ";
    }
    cout << endl;

    // Continue in a while loop
    cout << "\n=== Continue in a While ===" << endl;
    int i = 0;
    while (i < 10) {
        i++;
        if (i % 3 == 0) continue;
        cout << i << " ";
    }
    cout << endl;

    // Return in a search
    cout << "\n=== Return in a Search ===" << endl;
    int data[] = {10, 25, 30, 45, 50, 65, 70};
    int size = sizeof(data) / sizeof(data[0]);

    int target = 45;
    int index = findValue(data, size, target);
    if (index != -1) {
        cout << "Value " << target << " found at index " << index << endl;
    } else {
        cout << "Value " << target << " not found." << endl;
    }

    // Return in a prime check
    cout << "\n=== Return in a Prime Function ===" << endl;
    cout << "Prime numbers between 1-30:" << endl;
    for (int i = 1; i <= 30; i++) {
        if (isPrime(i)) {
            cout << i << " ";
        }
    }
    cout << endl;

    // Goto - break out of a nested loop
    cout << "\n=== Goto (Labeled Break) ===" << endl;
    for (int row = 1; row <= 5; row++) {
        for (int col = 1; col <= 5; col++) {
            if (row == 3 && col == 3) {
                cout << "\nFound at (3,3), exiting all!" << endl;
                goto done;
            }
            cout << "(" << row << "," << col << ") ";
        }
        cout << endl;
    }
    done:
    cout << "Program finished." << endl;

    // Goto for error handling (controversial usage)
    cout << "\n=== Goto for Error Handling ===" << endl;
    int* ptr = nullptr;

    if (ptr == nullptr) {
        cout << "Pointer is null, jumping to the error handler." << endl;
        goto error_handler;
    }

    // Code that uses ptr (will not be executed)
    cout << "Pointer value: " << *ptr << endl;

    error_handler:
    cout << "Error: Invalid pointer!" << endl;
    cout << "Program continues..." << endl;

    // Break in a switch
    cout << "\n=== Break in a Switch ===" << endl;
    char op;
    cout << "Operator (+, -, *, /): ";
    cin >> op;

    switch (op) {
        case '+':
            cout << "Addition operation" << endl;
            break;
        case '-':
            cout << "Subtraction operation" << endl;
            break;
        case '*':
            cout << "Multiplication operation" << endl;
            break;
        case '/':
            cout << "Division operation" << endl;
            break;
        default:
            cout << "Invalid operator" << endl;
            break;
    }

    // Break and continue together
    cout << "\n=== Break and Continue ===" << endl;
    for (int i = 1; i <= 20; i++) {
        if (i % 5 == 0) {
            cout << "\nMultiple of 5 found: " << i << ", stopping!" << endl;
            break;
        }
        if (i % 2 == 0) continue;
        cout << i << " ";
    }
    cout << endl;

    return 0;
}

Code Explanation

  • Break: Stops the execution of a loop (for, while, do-while) or a switch. After break, execution continues with the statement after the loop/switch. In a nested loop, break only exits the innermost loop.
  • Continue: Skips the rest of the code in the current iteration and moves on to the next iteration. In a for loop, the update part still runs. In a while loop, be careful not to forget updating the control variable.
  • Return: Returns a value from a function and immediately stops the function's execution. If the function returns no value (void), use return without a value or let the function end naturally.
  • Goto: Jumps to a label defined within the same function. Its use is controversial because it can make code hard to understand ("spaghetti code"). However, it is useful for breaking out of nested loops. A label is defined with a name followed by a colon (label:).

Everyday Use Cases

Data Search:

#include <iostream>
#include <string>
using namespace std;

struct Contact {
    string name;
    string phone;
};

int main() {
    Contact list[] = {
        {"Mike", "081234567890"},
        {"John", "085678901234"},
        {"Anna", "089012345678"},
        {"Dana", "082345678901"},
        {"Eric", "086789012345"}
    };
    int contactCount = sizeof(list) / sizeof(list[0]);

    cout << "=== Phone Book ===" << endl;
    cout << "Saved contacts:" << endl;
    for (int i = 0; i < contactCount; i++) {
        cout << (i + 1) << ". " << list[i].name << " - " << list[i].phone << endl;
    }

    string searchName;
    cout << "\nSearch for a contact: ";
    getline(cin, searchName);

    bool found = false;
    for (int i = 0; i < contactCount; i++) {
        if (list[i].name == searchName) {
            cout << "\nContact found!" << endl;
            cout << "Name   : " << list[i].name << endl;
            cout << "Phone  : " << list[i].phone << endl;
            found = true;
            break;
        }
    }

    if (!found) {
        cout << "Contact \"" << searchName << "\" not found." << endl;
    }

    return 0;
}

Input Validation:

#include <iostream>
using namespace std;

int main() {
    int choice;

    do {
        cout << "\n=== Main Menu ===" << endl;
        cout << "1. View Data" << endl;
        cout << "2. Add Data" << endl;
        cout << "3. Delete Data" << endl;
        cout << "4. Settings" << endl;
        cout << "0. Exit" << endl;
        cout << "Choice: ";

        if (!(cin >> choice)) {
            cout << "Input must be a number!" << endl;
            cin.clear();
            cin.ignore(10000, '\n');
            continue;
        }

        switch (choice) {
            case 1:
                cout << "Displaying data..." << endl;
                break;
            case 2:
                cout << "Adding data..." << endl;
                break;
            case 3:
                cout << "Deleting data..." << endl;
                break;
            case 4:
                cout << "Opening settings..." << endl;
                break;
            case 0:
                cout << "Thank you for using this program." << endl;
                break;
            default:
                cout << "Invalid choice! Please try again." << endl;
        }
    } while (choice != 0);

    return 0;
}

When to Use Each Jump Statement

Statement When to Use
break Exit a loop or switch early
continue Skip a particular iteration in a loop
return Return a value from a function
goto Break out of a nested loop or error handling (use rarely)

Conclusion

Jump statements (break, continue, return, goto) control the program's execution flow. break exits a loop/switch, continue skips the current iteration, return exits a function with a return value, and goto jumps to a label. Use goto carefully and only for cases such as breaking out of a nested loop. Understand that break only exits the innermost loop, while goto can exit from multiple levels at once.