Open In App

Switch Statement in C

Improve
Improve
Like Article
Like
Save
Share
Report

Switch case statement evaluates a given expression and based on the evaluated value(matching a certain condition), it executes the statements associated with it. Basically, it is used to perform different actions based on different conditions(cases). 

  • Switch case statements follow a selection-control mechanism and allow a value to change control of execution.
  • They are a substitute for long if statements that compare a variable to several integral values.
  • The switch statement is a multiway branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression.

In C, the switch case statement is used for executing one condition from multiple conditions. It is similar to an if-else-if ladder.

The switch statement consists of conditional-based cases and a default case.

Syntax of switch Statement in C

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

default: default_statement;
}

How to use switch case Statement in C?

Before using the switch case in our program, we need to know about some rules of the switch statement.

Rules of the switch case statement

Following are some of the rules that we need to follow while using the switch statement:

  1. In a switch statement, the “case value” must be of “char” and “int” type.
  2. There can be one or N number of cases.
  3. The values in the case must be unique.
  4. Each statement of the case can have a break statement. It is optional.
  5. The default Statement is also optional.

Example

C




// C program to Demonstrate returning of day based numeric
// value
#include <stdio.h>
 
int main()
{
  // switch variable
    int var = 1;
 
  // switch statement
    switch (var) {
        case 1:
            printf("Case 1 is Matched.");
            break;
 
        case 2:
            printf("Case 2 is Matched.");
            break;
 
        case 3:
            printf("Case 3 is Matched.");
            break;
 
        default:
            printf("Default case is Matched.");
            break;
    }
 
    return 0;
}


Output

Case 1 is Matched.

How switch Statement Work?

The working of the switch statement in C is as follows:

  1. Step 1: The switch variable is evaluated.
  2. Step 2: The evaluated value is matched against all the present cases.
  3. Step 3A: If the matching case value is found, the associated code is executed.
  4. Step 3B: If the matching code is not found, then the default case is executed if present.
  5. Step 4A: If the break keyword is present in the case, then program control breaks out of the switch statement.
  6. Step 4B: If the break keyword is not present, then all the cases after the matching case are executed.
  7. Step 5: Statements after the switch statement are executed.

We can also understand the working of the switch statement in C using the flowchart.

Flowchart of Switch Statement

switch case in c

Flowchart of switch statement in C

Break in switch case

This keyword is used to stop the execution inside a switch block. It helps to terminate the switch block and break out of it. When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.

The break statement is optional. If omitted, execution will continue on into the next case. The flow of control will fall through to subsequent cases until a break is reached.

Example of switch case without break

C




// C Program to demonstrate the behaviour of switch case
// without break
#include <stdio.h>
 
int main()
{
 
    int var = 2;
 
    // switch case without break
    switch (var) {
      case 1:
          printf("Case 1 is executed.\n");
      case 2:
          printf("Case 2 is executed.\n");
      case 3:
          printf("Case 3 is executed.");
      case 4:
          printf("Case 4 is executed.");
    }
    return 0;
}


Output

Case 2 is executed.
Case 3 is executed.Case 4 is executed.

Default in switch case

The default keyword is used to specify the set of statements to execute if there is no case match

It is optional to use the default keyword in a switch case. Even if the switch case statement does not have a default statement, it would run without any problem.

Important Points About Switch Case Statements

1. Switch expression should result in a constant value

If the expression provided in the switch statement does not result in a constant value, it would not be valid. Some valid expressions for switch case will be,

// Constant expressions allowed
switch(1+2+23)
switch(1*2+3%4)

// Variable expression are allowed provided
// they are assigned with fixed values
switch(a*b+c*d)
switch(a+b+c)

2. Expression value should be only of int or char type.

The switch statement can only evaluate the integer or character value. So the switch expression should return the values of type int or char only.

3. Case Values must be Unique

In the C switch statement, duplicate case values are not allowed.

3. Nesting of switch Statements

Nesting of switch statements is allowed, which means you can have switch statements inside another switch. However nested switch statements should be avoided as it makes the program more complex and less readable.

Examples of switch Statement in C

Example 1:  C Program to print the day of the week using a switch case.

C




// C program to print the day using switch
#include <stdio.h>
 
// Driver Code
int main()
{
    int day = 2;
 
    printf("The day with number %d is ", day);
    switch (day) {
      case 1:
          printf("Monday");
          break;
      case 2:
          printf("Tuesday");
          break;
      case 3:
          printf("Wednesday");
          break;
      case 4:
          printf("Thursday");
          break;
      case 5:
          printf("Friday");
          break;
      case 6:
          printf("Saturday");
          break;
      case 7:
          printf("Sunday");
          break;
      default:
          printf("Invalid Input");
          break;
      }
    return 0;
}


Output

The day with number 2 is Tuesday

Example 2: Simple Calculator using switch case in C

C




// C Program to create a simple calculator using switch
// statement
#include <stdio.h>
#include <stdlib.h>
 
// driver code
int main()
{
    // switch variable
    char choice;
    // operands
    int x, y;
 
    while (1) {
        printf("Enter the Operator (+,-,*,/)\nEnter x to "
               "exit\n");
        scanf(" %c", &choice);
 
        // for exit
        if (choice == 'x') {
            exit(0);
        }
 
        printf("Enter the two numbers: ");
        scanf("%d %d", &x, &y);
 
        // switch case with operation for each operator
        switch (choice) {
          case '+':
              printf("%d + %d = %d\n", x, y, x + y);
              break;
 
          case '-':
              printf("%d - %d = %d\n", x, y, x - y);
              break;
 
          case '*':
              printf("%d * %d = %d\n", x, y, x * y);
              break;
          case '/':
              printf("%d / %d = %d\n", x, y, x / y);
              break;
          default:
              printf("Invalid Operator Input\n");
        }
    }
    return 0;
}


Output

Enter the operator (+, -, *, /)

Enter x to exit

+
Enter the two numbers: 100 + 200
100 + 200 = 300

Advantages of C switch Statement

  1. Easier to read than if else if.
  2. Easier to debug and maintain for a large number of conditions.
  3. Faster execution speed.

Disadvantages of C switch Statement

  1. Switch case can only evaluate int or char type.
  2. No support for logical expressions.
  3. Have to keep in mind to add a break in every case.

Conclusion

In this article, we discussed the switch statement in C programming and how to use it. It is a conditional statement like the if-else-if ladder having its own merits and demerits. It is mostly preferred when the number of conditions to evaluate is large.

FAQs on C switch Statement

1. What is the switch case in C?

The switch case statement is a flow control statement in which we can define a switch variable and then execute different code based on the value of the switch variable. It is an alternative of if else if ladder.

2. What is the case in the switch statement in C?

The case keyword is used to define the different cases and their associated code in the switch statement.

3. What does the break in the switch case do?

The break keyword is used to exit the switch block after executing the matching case.

4. What are the differences between switch and if else if ladder in C?

Following are the main differences between C switch and C if else if ladder:

switch

if else if

It executes the different cases on the basis of the value of the switch variable. It executes the different blocks based on the condition specified.
It can only evaluate the int or char type expressions. It can evaluate any type of expression.
Faster and easier to read for the large number of conditions. It can get messy when there are lots of conditions.

Must Read:



Last Updated : 18 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads