C++ provides statements break and continue to alter the flow of the control. Given below I have explained how break can be used to terminate a switch statement’s execution. This article discusses how to use break in a repetition statement.
the break statement, when executed in a while, for, do...while or switch statement, causes immediate exit from that statement. Program execution continues with the next statement. Common uses of a switch statement are to escape early from a loop or to skip the remainder of a switch statement. There is code given ahead in the article that demonstrates the break statement exiting a for repetition statement.
When the if statement detects that count is 5, the break statement executes. This terminates the for statement, and the program proceeds to line 18 (immediately after the for statement), which displays a message indicating the control variable value that terminated the loop. The for statement fully executes its body only four times instead of 10. The control variable count is defined outside the for statement header, so that we can use the control variable both in the loop’s body and after the loop completes its execution.
using namespace std;
unsigned int count; //control variable also used after loop terminates
for ( count = 1; count <= 10; ++count) //loop 10 times
if ( count == 5 )
break; // break loop only if count is 5
cout << count << " " ;
} // end for
cout << "\nBroke out of loop at count = " << count < endl;
// end main
1 2 3 4 5
Broke out of loop at count = 5