What is the break keyword in C++?
Overview
The break keyword in C++ is used to break out of a switch block. This stops the execution of subsequent code inside the block. When a match is found in the switch block, the job is done. Therefore, there’s no need for more testing.
Note: The switch statements are a block of code that act like an if-else-if statement.
The break keyword saves a lot of time for execution. This is because it ignores the execution of the subsequent code in the switch block when a match is found.
Code
#include <iostream>using namespace std;int main() {int month = 5;switch (month) {case 1:cout << "January";break;case 2:cout << "Februray";break;case 3:cout << "March";break;case 4:cout << "April";break;case 5:cout << "May";break;case 6:cout << "June";break;case 7:cout << "July";break;case 8:cout << "August";break;case 9:cout << "Septembe";break;case 10:cout << "October";break;case 11:cout << "November";break;case 12:cout << "December";break;}return 0;}
Explanation
From the code above, we notice that there is a break immediately after there is a match in case 5 for int month = 5. At this point, the result is May. The rest of the code is ignored. This is possible because of the break keyword.