• Home
  • 4.6 break Statement

4.6 break Statement

View Categories

4.6 break Statement

Table of Contents

The break statement immediately terminates the nearest enclosing loop or switch statement. Program execution continues with the first statement following that loop or switch.

In a switch statement, break is commonly used at the end of each case to prevent execution from continuing into subsequent cases.

Source Code #

#include <iostream>

int main()
{
    int day = 2;

    switch (day)
    {
        case 1:
            std::cout << "Monday\n";
            break;

        case 2:
            std::cout << "Tuesday\n";
            break;

        case 3:
            std::cout << "Wednesday\n";
            break;

        default:
            std::cout << "Invalid day\n";
            break;
    }

    std::cout << "Switch completed.\n";

    return 0;
}

Output #

Tuesday
Switch completed.

Explanation #

  • The break statement immediately terminates the nearest enclosing switch or loop.
  • When day is 2, case 2 is selected and "Tuesday" is printed.
  • break; then terminates the switch statement.
  • Execution continues with the statement following the switch block.
  • Without break, execution could continue into the statements of subsequent cases, resulting in fallthrough.
  • A break statement affects only the nearest enclosing loop or switch statement.
  • break does not terminate the entire program; execution continues normally after the enclosing construct.
  • return 0; terminates the program successfully.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *