Break Statement
C++ break Statement
In C++, the break statement is used to terminate the execution of a loop or switch statement prematurely. When the break statement is encountered inside a loop or switch, the control is transferred immediately to the statement following the loop or switch.
Example using break within a for loop:
#include <iostream>
int main() {
for (int i = 1; i <= 10; ++i) {
if (i == 5) {
std::cout << "Breaking out of the loop at i = " << i << std::endl;
break;
}
std::cout << i << " ";
}
return 0;
}
Output:
1 2 3 4 Breaking out of the loop at i = 5
In this example, the loop is designed to print numbers from 1 to 10. However, when i becomes 5, the break statement is encountered, and the loop is immediately terminated.
Example using break within a switch statement:
#include <iostream>
int main() {
int choice;
std::cout << "Enter a choice (1-3): ";
std::cin >> choice;
switch (choice) {
case 1:
std::cout << "You selected option 1." << std::endl;
break;
case 2:
std::cout << "You selected option 2." << std::endl;
break;
case 3:
std::cout << "You selected option 3." << std::endl;
break;
default:
std::cout << "Invalid choice." << std::endl;
break;
}
return 0;
}
In this example, if the user enters a choice outside the range 1-3, the default case is executed, and the break statement ensures that the switch statement is exited.
The break statement is a crucial tool for controlling the flow of loops and switch statements, allowing you to exit the loop or switch under specific conditions.