C++ Break Statement
The break statement in C++ is used to immediately terminate a loop or a switch statement. When the break statement is encountered, the program exits the current loop or switch block and continues execution with the next statement after it.
The break statement is commonly used inside for, while, do while loops and switch statements to stop execution based on a condition.
Syntax
break;
Break Statement in a Loop
The break statement can be used inside loops to stop the loop when a specific condition is met.
#include <iostream>
using namespace std;
int main() {
for(int i = 1; i <= 10; i++) {
if(i == 5) {
break;
}
cout << i << " ";
}
return 0;
}
Output
1 2 3 4
Break Statement in Switch
The break statement is commonly used in a switch statement to stop execution after a matching case is found.
#include <iostream>
using namespace std;
int main() {
int day = 2;
switch(day) {
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
default:
cout << "Invalid day";
}
return 0;
}
Important Notes
- The break statement stops the current loop or switch statement immediately.
- It helps prevent unnecessary loop iterations.
- In switch statements, break prevents execution from continuing to the next case.
- If break is not used in a switch statement, execution continues to the next case (called fall-through).
Next Topic
Next, learn about the C++ Continue Statement.