Namespaces
Variants
Views
Actions

break statement

From cppreference.com
< cpp‎ | language
Revision as of 17:41, 31 October 2014 by Kumiponi (Talk | contribs)

 
 
C++ language
General topics
Flow control
Conditional execution statements
if
Iteration statements (loops)
for
range-for (C++11)
Jump statements
continue - break
Functions
Function declaration
Lambda function expression
inline specifier
Dynamic exception specifications (until C++17*)
noexcept specifier (C++11)
Exceptions
Namespaces
Types
Specifiers
const/volatile
decltype (C++11)
auto (C++11)
constexpr (C++11)
consteval (C++20)
constinit (C++20)
Storage duration specifiers
Initialization
Expressions
Alternative representations
Literals
Boolean - Integer - Floating-point
Character - String - nullptr (C++11)
User-defined (C++11)
Utilities
Attributes (C++11)
Types
typedef declaration
Type alias declaration (C++11)
Casts
Memory allocation
Classes
Class-specific function properties
explicit (C++11)
static

Special member functions
Templates
Miscellaneous
 
 

Causes the enclosing for, range-for, while or do-while loop or switch statement to terminate.

Used when it is otherwise awkward to terminate the loop using the condition expression and conditional statements.

Contents

Syntax

attr(optional) break ;

Explanation

After this statement the control is transferred to the statement immediately following the enclosing loop. All automatic storage objects declared in enclosing loop are destroyed before the execution of the first line following the enclosing loop.

Note: A single break statement cannot be used to break out of multiple nested loops. The goto statement, that is otherwise rarely used, is sometimes used for this purpose.

Keywords

break

Example

#include <iostream>
 
int main()
{
    int i = 2;
    switch (i) {
        case 1: std::cout << "1";
        case 2: std::cout << "2";   //execution starts at this case label
        case 3: std::cout << "3";
        case 4:
        case 5: std::cout << "45";
                break;              //execution of subsequent statements is terminated
        case 6: std::cout << "6";
    }
 
    std::cout << '\n';
 
    for (int j = 0; j < 2; j++) {
        for (int k = 0; k < 5; k++) {         //only this loop is affected by break
            if (k == 2) break;
            std::cout << j << k << " ";
        }
    }
}

Output:

2345
00 01 10 11