Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

keywords
c++
communitycreator
break

What is the break keyword in C++?

Onyejiaku Theophilus Chidalu

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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;
}
Implementing the break keyword in a C++ program

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.

RELATED TAGS

keywords
c++
communitycreator
break

CONTRIBUTOR

Onyejiaku Theophilus Chidalu

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring