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
switch
statement.
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
for
loop iterates from 1 to 10. - When
i == 5
, thebreak
statement 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
choice
is set to2
. - The
switch
statement evaluates the value ofchoice
. - Case
2
is executed, printing “You selected option 2.” - The
break
statement exits theswitch
block, 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
i
from 1 to 3, and the inner loop iterates overj
from 1 to 3. - When
j == 2
, thebreak
statement 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
break
keyword is used to terminate the execution of the nearest enclosing loop orswitch
statement. - It helps prevent unnecessary iterations or case executions.
- In nested loops,
break
only exits the innermost loop where it is used.