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

Switch Statement in C

Last Updated : 11 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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. If you’re looking to master decision-making structures and how they relate to data structures, the C Programming Course Online with Data Structures offers detailed lessons on control flow and advanced programming concepts.

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.

Switch Statement in C – FAQs

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.

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.

What does the break in the switch case do?

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

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

  • It executes the different cases on the basis of the value of the switch variable.
  • It can only evaluate the int or char type expressions.
  • Faster and easier to read for the large number of conditions.

if else if

  • It executes the different blocks based on the condition specified.
  • It can evaluate any type of expression.
  • 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<stdio.h> int main() { int i = 10; int c = 10; switch(c) { case i: // not a "const int" expression printf("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 &lt;stdio.h&gt; int main() { int x = 2; switch (x) { case 1: printf(&quot;Choice is 1&quot;); break; case 2: printf(&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 <stdio.h> int main() { int num = 2; switch (num + 2) { case 1: printf("Case 1: "); case 2: printf("Case 2: "); case 3: printf("Case 3: "); default: printf("Default: "); } 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 (==, <,>,...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 <stdlib.h> 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
C if...else Statement
The if-else statement in C is a flow control statement used for decision-making in the C program. It is one of the core concepts of C programming. It is an extension of the if in C that includes an else block along with the already existing if block. C if Statement The if statement in C is used to execute a block of code based on a specified condit
6 min read
Return Statement in C
Pre-requisite: Functions in C C return statement ends the execution of a function and returns the control to the function from where it was called. The return statement may or may not return a value depending upon the return type of the function. For example, int returns an integer value, void returns nothing, etc. In C, we can only return a single
4 min read
C - if Statement
The if in C is the most simple decision-making statement. It consists of the test condition and if block or body. If the given condition is true only then the if block will be executed. What is if in C? The if in C is a decision-making statement that is used to execute a block of code based on the value of the given expression. It is one of the cor
5 min read
Implementing ternary operator without any conditional statement
How to implement ternary operator in C++ without using conditional statements.In the following condition: a ? b: c If a is true, b will be executed. Otherwise, c will be executed.We can assume a, b and c as values. 1. Using Binary Operator We can code the equation as : Result = (!!a)*b + (!a)*c In above equation, if a is true, the result will be b.
4 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
Continue Statement in C
The continue statement in C is a jump statement that is used to bring the program control to the start of the loop. We can use the continue statement in the while loop, for loop, or do..while loop to alter the normal flow of the program execution. Unlike break, it cannot be used with a C switch case. What is continue in C?The C continue statement r
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 tells th
3 min read
C Programming Language Tutorial
In this C Tutorial, you’ll learn all C programming basic to advanced concepts like variables, arrays, pointers, strings, loops, etc. This C Programming Tutorial is designed for both beginners as well as experienced professionals, who’re looking to learn and enhance their knowledge of the C programming language. What is C?C is a general-purpose, pro
8 min read
Pattern Programs in C
Printing patterns using C programs has always been an interesting problem domain. We can print different patterns like star patterns, pyramid patterns, Floyd's triangle, Pascal's triangle, etc. in C language. These problems generally require the knowledge of loops and if-else statements. In this article, we will discuss the following example progra
15+ min read
C Programs
To learn anything effectively, practicing and solving problems is essential. To help you master C programming, we have compiled over 100 C programming examples across various categories, including basic C programs, Fibonacci series, strings, arrays, base conversions, pattern printing, pointers, and more. These C Examples cover a range of questions,
9 min read
Switch Statement in C
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
8 min read
scanf in C
In C programming language, scanf is a function that stands for Scan Formatted String. It is used to read data from stdin (standard input stream i.e. usually keyboard) and then writes the result into the given arguments. It accepts character, string, and numeric data from the user using standard input.scanf also uses format specifiers like printf.sc
2 min read
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
Since C is a structured language, it has some fixed rules for programming. One of them includes changing the size of an array. An array is a collection of items stored at contiguous memory locations. As can be seen, the length (size) of the array above is 9. But what if there is a requirement to change this length (size)? For example, If there is a
9 min read
Substring in C++
The substring function is used for handling string operations like strcat(), append(), etc. It generates a new string with its value initialized to a copy of a sub-string of this object. In C++, the header file which is required for std::substr(), string functions is <string>. The substring function takes two values pos and len as an argument
8 min read
Strings in C
A String in C programming is a sequence of characters terminated with a null character '\0'. The C String is stored as an array of characters. The difference between a character array and a C string is that the string in C is terminated with a unique character '\0'. C String Declaration SyntaxDeclaring a string in C is as simple as declaring a one-
8 min read
Decision Making in C (if , if..else, Nested if, if-else-if )
The conditional statements (also known as decision control structures) such as if, if else, switch, etc. are used for decision-making purposes in C programs. They are also known as Decision-Making Statements and are used to evaluate one or more conditions and make the decision whether to execute a set of statements or not. These decision-making sta
11 min read
Operators in C
In C language, operators are symbols that represent operations to be performed on one or more operands. They are the basic components of the C programming. In this article, we will learn about all the built-in operators in C with examples. What is a C Operator?An operator in C can be defined as the symbol that helps us to perform some specific math
14 min read
C Pointers
Pointers are one of the core components of the C programming language. A pointer can be used to store the memory address of other variables, functions, or even other pointers. The use of pointers allows low-level memory access, dynamic memory allocation, and many other functionality in C. In this article, we will discuss C pointers in detail, their
14 min read
Data Types in C
Each variable in C has an associated data type. It specifies the type of data that the variable can store like integer, character, floating, double, etc. Each data type requires different amounts of memory and has some specific operations which can be performed over it. The data types in C can be classified as follows: Types Description Data Types
7 min read
C Arrays
Array in C is one of the most used data structures in C programming. It is a simple and fast way of storing multiple values under a single name. In this article, we will study the different aspects of array in C language such as array declaration, definition, initialization, types of arrays, array syntax, advantages and disadvantages, and many more
15+ min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The & (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1. The | (bitwise OR) in C takes two nu
7 min read
C Language Introduction
C is a procedural programming language initially developed by Dennis Ritchie in the year 1972 at Bell Laboratories of AT&T Labs. It was mainly developed as a system programming language to write the UNIX operating system. The main features of the C language include: General Purpose and PortableLow-level Memory AccessFast SpeedClean SyntaxThese
6 min read
three90RightbarBannerImg