C++ break Keyword
The break keyword in C++ is used to immediately terminate the execution of the innermost for, while, do-while loop, or a switch statement. When the break statement is encountered, the control exits the current loop or switch block and proceeds to the next statement after it.
The break statement is particularly useful for exiting loops prematurely based on certain conditions, avoiding unnecessary iterations.
Syntax
</>
Copy
break;
- break
- The keyword used to terminate the execution of the nearest enclosing loop or
switchstatement.
Examples
Example 1: Using break in a Loop
This example demonstrates how to use the break statement to terminate a loop when a specific condition is met.
</>
Copy
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 10; ++i) {
if (i == 5) {
break; // Exit the loop when i equals 5
}
cout << i << " ";
}
cout << "Loop terminated." << endl;
return 0;
}
Output:
1 2 3 4 Loop terminated.
Explanation:
- The
forloop iterates from 1 to 10. - When
i == 5, thebreakstatement is executed, immediately terminating the loop. - The program prints numbers from 1 to 4 and exits the loop, displaying “Loop terminated.”
Example 2: Using break in a switch Statement
This example demonstrates how to use the break statement to exit a switch case block.
</>
Copy
#include <iostream>
using namespace std;
int main() {
int choice = 2;
switch (choice) {
case 1:
cout << "You selected option 1." << endl;
break; // Exit the switch block
case 2:
cout << "You selected option 2." << endl;
break; // Exit the switch block
case 3:
cout << "You selected option 3." << endl;
break; // Exit the switch block
default:
cout << "Invalid choice." << endl;
}
return 0;
}
Output:
You selected option 2.
Explanation:
- The variable
choiceis set to2. - The
switchstatement evaluates the value ofchoice. - Case
2is executed, printing “You selected option 2.” - The
breakstatement exits theswitchblock, preventing the execution of subsequent cases.
Example 3: Using break in a Nested Loop
This example shows how the break statement behaves in a nested loop structure.
</>
Copy
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 3; ++i) {
for (int j = 1; j <= 3; ++j) {
if (j == 2) {
break; // Exit the inner loop
}
cout << "i: " << i << ", j: " << j << endl;
}
}
return 0;
}
Output:
i: 1, j: 1
i: 2, j: 1
i: 3, j: 1
Explanation:
- The outer loop iterates over
ifrom 1 to 3, and the inner loop iterates overjfrom 1 to 3. - When
j == 2, thebreakstatement is executed, terminating the inner loop. - The outer loop continues to the next iteration, starting the inner loop again.
Key Points about break Keyword
- The
breakkeyword is used to terminate the execution of the nearest enclosing loop orswitchstatement. - It helps prevent unnecessary iterations or case executions.
- In nested loops,
breakonly exits the innermost loop where it is used.
