The Wayback Machine - https://web.archive.org/web/20240630150335/https://www.geeksforgeeks.org/c-switch-statement/
Open In App

Switch Statement in C

Last Updated : 17 Apr, 2024
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.

4. The default block can be placed anywhere

Regardless of its placement, the default case only gets executed if none of the other case conditions are met. So, putting it at the beginning, middle, or end doesn’t change the core logic.

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:



Previous Article
Next Article

Similar Reads

Data type of case labels of switch statement in C++?
In C++ switch statement, the expression of each case label must be an integer constant expression. For example, the following program fails in compilation. C/C++ Code /* Using non-const in case label */ #include&lt;stdio.h&gt; int main() { int i = 10; int c = 10; switch(c) { case i: // not a &quot;const int&quot; expression printf(&quot;Value of c
2 min read
Interesting facts about switch statement in C
Prerequisite - Switch Statement in C Switch is a control statement that allows a value to change control of execution. C/C++ Code // Following is a simple program to demonstrate syntax of switch. #include &amp;lt;stdio.h&amp;gt; int main() { int x = 2; switch (x) { case 1: printf(&amp;quot;Choice is 1&amp;quot;); break; case 2: printf(&amp;quot;Cho
3 min read
Print individual digits as words without using if or switch
Given a number, print words for individual digits. It is not allowed to use if or switch.Examples: Input: n = 123 Output: One Two Three Input: n = 350 Output: Three Five Zero We strongly recommend you to minimize your browser and try this yourself first. The idea is to use an array of strings to store digit to word mappings. Below are steps.Let the
5 min read
Output of C programs | Set 30 (Switch Case)
Prerequisite - Switch Case in C/C++ Interesting Problems of Switch statement in C/C++ Program 1 #include &lt;stdio.h&gt; int main() { int num = 2; switch (num + 2) { case 1: printf(&quot;Case 1: &quot;); case 2: printf(&quot;Case 2: &quot;); case 3: printf(&quot;Case 3: &quot;); default: printf(&quot;Default: &quot;); } return 0; } Output: Default:
2 min read
Using Range in switch Case in C
You all are familiar with switch case in C, but did you know you can use a range of numbers instead of a single number or character in the case statement? Range in switch case can be useful when we want to run the same set of statements for a range of numbers so that we do not have to write cases separately for each value. That is the case range ex
2 min read
Print "Even" or "Odd" without using conditional statement
Write a program that accepts a number from the user and prints "Even" if the entered number is even and prints "Odd" if the number is odd. You are not allowed to use any comparison (==, &lt;,&gt;,...etc) or conditional statements (if, else, switch, ternary operator,. Etc). Method 1 Below is a tricky code can be used to print "Even" or "Odd" accordi
4 min read
Return Statement vs Exit() in main() in C++
The return statement in C++ is a keyword used to return the program control from the called function to the calling function. On the other hand, the exit() function in C is a standard library function of &lt;stdlib.h&gt; that is used to terminate the process explicitly. The operation of the two may look different but in the case of the main() funct
3 min read
C++ Break Statement
The break in C++ is a loop control statement that is used to terminate the loop. As soon as the break statement is encountered from within a loop, the loop iterations stop there and control returns from the loop immediately to the first statement after the loop. Syntax: break; Basically, break statements are used in situations when we are not sure
5 min read
goto Statement in C
The C goto statement is a jump statement which is sometimes also referred to as an unconditional jump statement. The goto statement can be used to jump from anywhere to anywhere within a function. Syntax: Syntax1 | Syntax2 ---------------------------- goto label; | label: . | . . | . . | . label: | goto label; In the above syntax, the first line te
3 min read
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 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.
6 min read
three90RightbarBannerImg