break statement - cppreference.com

From cppreference.com

Terminates specific enclosing statements.

Syntax

attr(optional)break;Explanation

break statements must be

enclosed

by any of the following statements:

iteration statements

(

for

,

range-for

,

while

or

do-while

)

switch

statements

Executing a break statement causes termination of the innermost such enclosing statement, then control passes to the statement following the terminated statement (if any).

Notes

As with any block exit, all automatic storage objects declared in enclosing compound statement or in the condition of a loop/switch are destroyed, in reverse order of construction, before the execution of the first line following the enclosing loop.

A break statement cannot be used to break out of multiple nested loops. The

goto

statement may be used for this purpose.

Keywords

break

Example

Run this code

#include<iostream>intmain(){inti=2;switch(i){case1:std::cout<<"1";// <---- maybe warning: fall throughcase2:std::cout<<"2";// execution starts at this case label (+warning)case3:std::cout<<"3";// <---- maybe warning: fall throughcase4:// <---- maybe warning: fall throughcase5:std::cout<<"45";//break;// execution of subsequent statements is terminatedcase6:std::cout<<"6";}std::cout<<'\n';for(charc='a';c<'c';c++){for(inti=0;i<5;i++)// only this loop is affected by break{//if(i==2)//break;//std::cout<<c<<i<<' ';//}}std::cout<<'\n';}Possible output:

2345 a0 a1 b0 b1 See also

(C++17)

indicates that the fall through from the previous case label is intentional and should not be diagnosed by a compiler that warns on fall-through
(attribute specifier)

[edit]