C++ Break Statement

Break statement in C++ is used to terminate the current scope. This can be used anywhere in program. Most commonly it is used in two types of control strutures.

  • 1. Selection
  • 2. Iteration

It is an important part of switch statement in C++. Whenever it comes in statement block, control exist from block.

Example

Example of break statement is as given.

break statement with switch

#include <iostream>
using namespace std;

int main(int argc, char** argv) {
	
	int a = 1;
	
	switch (a) {
		case 1:
			cout<<"One";
			break; // here break keyword is used
		case 2:
			cout<<"Two";
			break; // here break keyword is used
		default:
			cout<<"Other Number";
	}
	
	return 0;
}

break statement with while loop

#include <iostream>
using namespace std;

int main(int argc, char** argv) {
	
	int a = 1;
	
	while ( a<= 10) {
		if(a == 6)
		     break; // here break is used to terminate loop.
		cout<<a;
		a = a + 1; // here we can also write a++
	}
	
	return 0;
}

In the above example while loop will print counting just up to 5. Because when counter variable will 6 if condition terminate the loop using break statement.

 

Comments
Login to TRACK of Comments.