These are control statements that allow you to alter the normal flow of loops or program execution.
break
Statement
The break
statement is used to exit from the nearest enclosing loop or switch statement immediately. It stops the loop even if the loop condition is still true.
#include <iostream> using namespace std; int main() { for (int i = 1; i <= 10; i++) { if (i == 5) { break; // Exit loop when i is 5 } cout << i << " "; } return 0; }
Output: 1 2 3 4
The loop stops when i
becomes 5 because of the break
statement.
continue
Statement
The continue
statement skips the current iteration of the loop and proceeds with the next iteration.
#include <iostream> using namespace std; int main() { for (int i = 1; i <= 5; i++) { if (i == 3) { continue; // Skip when i is 3 } cout << i << " "; } return 0; }
Output: 1 2 4 5
The loop skips printing 3
because of continue
.
goto
Statement
The goto
statement transfers control unconditionally to a labeled statement within the same function. It is generally discouraged because it can make code harder to read and maintain, but can be useful in some scenarios.
goto label; ... label: // code to execute
#include <iostream> using namespace std; int main() { int num = 1; start: // label cout << "Number: " << num << endl; num++; if (num <= 5) { goto start; // jump to label } return 0; }
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Statement | Effect | Usage |
---|---|---|
break |
Exits the current loop or switch immediately. | Stop loop early based on condition. |
continue |
Skips current loop iteration and moves to next. | Skip processing certain values. |
goto |
Jumps to a labeled statement unconditionally. | Rare use cases; generally avoided for readability. |
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!