上QQ阅读APP看书,第一时间看更新
Jump statements
As well as condition and iteration statements, you also have break and continue statements.
The break statement is used to break out of an iteration. We can leave a loop and force it to quit if a certain condition is met.
Let's look at the break statement in use:
#include <iostream> #include <conio.h> // Program prints out values to screen int main() { for (int n = 0; n < 10; n++) { if (n == 5) { std::cout << "break" << std::endl; break; } std::cout << "value of n is: " << n << std::endl; } _getch(); return 0; }
The output of this is as follows:
The continue statement will skip the current iteration and continue the execution of the statement until the end of the loop. In the break code, replace the break with continue to see the difference:
#include <iostream> #include <conio.h> // Program prints out values to screen int main() { for (int n = 0; n < 10; n++) { if (n == 5) { std::cout << "continue" << std::endl; continue; } std::cout << "value of n is: " << n << std::endl; } _getch(); return 0; }
Here is the output when break is replaced with continue: