C++

With An Example, The C++ Break Statement – Q&A

The following two situations involve the use of the break statement:

a) To exit the loop immediately, use the break statement. The control exits the loop immediately upon encountering a break statement, ending the loop. When used inside of a loop (see the example below), it is combined with an if statement to ensure that it only happens under specific circumstances.

b) It follows the case blocks in the switch case control structure. In order to prevent the execution of the following cases (see the example below), every switch case case is typically preceded by a break statement. The control exits the switch-case body whenever it is met in a switch-case block.

Syntax of break statement

break;

Use of the break expression in a while loop as an example

The while loop in the example below runs from 10 to 200, but because a break statement is encountered when the loop counter variable value hits 12, the loop is terminated and control is transferred to the statement that follows the body of the loop.

#include <iostream>
using namespace std;
int main(){
   int num =10;
   while(num<=200) {
      cout<<"Value of num is: "<<num<<endl;
      if (num==12) {
         break;
      }
      num++;
   } 
   cout<<"Hey, I'm out of the loop";
   return 0;
}

Output:

Value of num is: 10
Value of num is: 11
Value of num is: 12
Hey, I'm out of the loop

For loop with a break clause as an example

#include <iostream>
using namespace std;
int main(){
   int var;
   for (var =200; var>=10; var --) {
      cout<<"var: "<<var<<endl;
      if (var==197) {
         break;
      }
   }
   cout<<"Hey, I'm out of the loop";
   return 0;
}

Output:

var: 200
var: 199
var: 198
var: 197
Hey, I'm out of the loop

Example: Switch Case with a break statement

#include <iostream>
using namespace std;
int main(){
   int num=2;
   switch (num) {
      case 1: cout<<"Case 1 "<<endl;
      break;
      case 2: cout<<"Case 2 "<<endl;
      break;
      case 3: cout<<"Case 3 "<<endl;
      break;
      default: cout<<"Default "<<endl;
   }
   cout<<"Hey, I'm out of the switch case";
   return 0;
}

Output:

Case 2 
Hey, I'm out of the switch case

Because the next case block would otherwise execute without a break statement, we have one in this example after each case block. Without a break, the identical program’s output would be:

Case 2
Case 3
Default
Hey, I'm out of the switch case

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button