The C++ statement called break
provides a way to break out a loop early. The break statement is placed within the body of the loop usually as part of an if statement.
In the example, the loop is set to run a maximum of 50 times but the user can quit the loop at any time by specifying a specific input, q
in this case.
break
?The use of break statements is not recommended. We expect the iteration of a loop to be controlled by the true/false statements in the while and do-while and the for loop header sections. Adding a means to suddenly stop the loop outside of the normal approach can make code difficult to understand and debug.
We can rewrite the above code to stop when the user enters q
without having to use a break statement such as follows.
break
in a nested loopIn a nested loop, a break statement only stops the loop it is placed in. Therefore, if a break is placed in the inner loop, the outer loop still continues. However, if the break is placed in the outer loop, all of the looping stops.