break statement

From Cppreference

Jump to: navigation, search

Causes the enclosing 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

[edit] Syntax

break

[edit] Explanation

After this statement the control is transferred to the statement following the enclosing loop.

[edit] Keywords

break

[edit] 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