break statement in C

The break statement terminates the execution of the nearest enclosing loop (whiledo while or for) and switch body. After termination of the loop or switch body, control passes to the statement that follows the terminated statement. Before using the break statement you should remember, the break statement shall appear only in a switch body or loop body.

Syntax:

break;

Flowchart of break (Jump statement)in C

 

break statement

 

How does break work in C?

Let see an example code to understand the working of the break statement. The below-mentioned code adds the positive enter numbers. If the user enters any negative number, then the program will be displayed the sum of all positive numbers and terminate.

 

break in c

 

Importance of break in switch case

In below example, if iChoice is equal to 1, all statements of the body are executed because there is no break statement appear in the body of the switch case. if ichoice equal to 2 then control jump to case 2 and execute all the below case since there is no break statement.

 

switch c code

 

We can resolve this problem using the break statement, see the below code.

Output:

Enter your choice = 1
case 1 !

Enter your choice = 2
case 2 !

 

As I mentioned at the beginning of this article is that within the nested loop or nested switch case, the break statement terminates the execution of the nearest enclosing loop or switch body.

Let consider an example to understand the above-mentioned statement. Suppose there are three loops (while loop) X, Y, and Z. The loop Z nested inside loop Y and Y is nested inside the loop X. There is three scenario comes after writing the break statement inside these loops.

1. break inside loop Z: It will break only loop Z, control still inside the loop Y.

break in c

 

2. break inside loop Y (but not inside the loop Z): It will break only loop Y, control still inside the loop X.

 

break statement in c

3. break inside loop X: It will break the only loop X.

 

break

 

In below example code, I have implemented break statement only in inner switch case( in case 1). What I want to show here if a break statement executes then it only terminates the nearest enclosing switch body.

When you compile the code, you will find that only inner switch case will be terminated and the break statement of inner switch case will not affect the outer switch case body.

 

break statement in c