c-plus-plus
  1. c-plus-plus-break-statement

C++ Control Statement: Break Statement

The break statement is part of the control statements in C++. It is used to terminate the execution of a loop or a switch statement. When the break statement is encountered within a loop or switch statement, the control transfers to the statement immediately following the loop or switch statement.

Syntax

The syntax for the break statement in C++ is as follows:

break;

Example

The following example demonstrates the use of the break statement in a for loop:

#include<iostream>
using namespace std;

int main() {
    for(int i = 0; i <= 10; i++) {
        if(i == 5) {
            break;
        }
        cout << i << endl;
    }
    cout << "Loop Terminated!" << endl;
    return 0;
}

Output

When run, the above program will output the following:

0
1
2
3
4
Loop Terminated!

Explanation

In the above example, a for loop is used to iterate from 0 through 10. Within the for loop, an if statement checks whether the current value of i is equal to 5. If i is equal to 5, the break statement is executed, which terminates the for loop. If i is not equal to 5, the current value of i is printed to the console.

When run, the program prints the values of 0, 1, 2, 3, and 4 before terminating the loop with the break statement. Finally, the program prints the message "Loop Terminated!" to the console.

Use

The break statement is used to prematurely terminate the execution of a loop or a switch statement, based on certain conditions. It is used when you need to exit from a loop or switch statement before it would normally end.

Important Points

  • The break statement can only be used within a loop or a switch statement.
  • When the break statement is executed, the control transfers to the statement immediately following the loop or switch statement.
  • If the break statement is not used within the loop or switch statement, the execution of the loop or switch statement continues until its normal termination.

Summary

The break statement is a control statement that is used to prematurely terminate the execution of a loop or switch statement in C++. When encountered within a loop or switch statement, the control transfers to the statement immediately following the loop or switch statement. Its use can help simplify code and improve its efficiency.

Published on: