Break in C switch case

In general, the Switch case statement evaluates an expression, and depending on the value of the expression, it executes the statement associated with the value. Not only that, all the cases after the matching case after the matching case will also be executed. To prevent that, we can use the break statement in the switch case as shown:

Syntax of break in switch case

switch(expression)
{    
case value1:
    statement_1;
    break;
    
case value2:
    statement_2;
    break;
.....
.....

case value_n:
    statement_n;
    break;
    
default:
    default statement;
}

Example of break in switch case

C




// C Program to demonstrate working of break with switch
// case
#include <stdio.h>
#include <stdlib.h>
 
int main()
{
    char c;
    float x, y;
 
    while (1) {
        printf("Enter an operator (+, -), if want to exit "
               "press x: ");
        scanf(" %c", &c);
        // to exit
        if (c == 'x')
            exit(0);
 
        printf("Enter Two Values:\n ");
        scanf("%f %f", &x, &y);
 
        switch (c) {
        // For Addition
        case '+':
            printf("%.1f + %.1f = %.1f\n", x, y, x + y);
            break;
        // For Subtraction
        case '-':
            printf("%.1f - %.1f = %.1f\n", x, y, x - y);
            break;
        default:
            printf(
                "Error! please write a valid operator\n");
        }
    }
}


Output:

Enter an operator (+, -), if want to exit press x: +
Enter Two Values:
10
20
10.0 + 20.0 = 30.0

Break Statement in C

The break statement is one of the four jump statements in the C language. The purpose of the break statement in C is for unconditional exit from the loop

Similar Reads

What is break in C?

The break in C is a loop control statement that breaks out of the loop when encountered. It can be used inside loops or switch statements to bring the control out of the block. The break statement can only break out of a single loop at a time....

Syntax of break in C

break;...

Use of break in C

The break statement in C is used for breaking out of the loop. We can use it with any type of loop to bring the program control out of the loop. In C, we can use the break statement in the following ways:...

Examples of break in C

Example 1: C Program to use break Statement with Simple Loops...

How break statement works?

...

Flowchart of break in C

...

Break in C switch case

...

Conclusion

Working of break in a for loop...

FAQs on C break Statement

...