Switch Statement in C

Switch Statement in C

The switch statement in C is a useful tool for making decisions in your code based on a specific value or variable. It’s like a roadmap that helps your program choose the right path to follow. Unlike long lists of if-else statements, the switch statement keeps things organized and efficient. In this guide, we’ll break down how the switch statement works in C, how to use it, and where it can come in handy to make your code more straightforward and easier to read. Whether you’re just starting to code or have some experience, the switch statement is a valuable tool to have in your C programming toolkit.

What is Switch Statement

A switch case statement in programming evaluates an expression and then, depending on the result (if it matches specific conditions), carries out certain actions. In simple terms, it’s like a tool to do different things based on different situations.

Switch case statements help with making choices in your code. They’re an alternative to using long if statements to check if a variable matches specific values. Think of them as a way to direct your program’s flow in various directions.

In technical terms, the switch statement is like a road with multiple branches. It directs your program to different sections of code based on the expression’s value. This makes it easier to handle various scenarios and keep your code organized.

Syntax Of Switch Statement

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 statements in C?

Rules of the switch case statement

In a switch statement:

  1. The “case value” can be of “char” and “int” type, meaning you can compare the switch expression to characters or integers.
  2. You can have one or multiple cases, allowing you to define different actions for different values.
  3. The values in the cases must be unique, ensuring that each case is distinct and does not overlap with others.
  4. Each statement within a case can have a break statement, which is optional. The break statement is used to exit the switch statement after a case is executed, preventing the code from falling through to subsequent cases.
  5. The default statement is also optional. It serves as a catch-all case when none of the other cases match the switch expression’s value. If present, the code within the default case will be executed.

Example

// 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 Does Switch Statement Work?

  1. First, the switch variable is evaluated.
  2. Then, the evaluated value is compared to all the cases present in the switch statement.
  3. If a matching case is found:
    • The code associated with that case is executed.
    • If there’s a “break” keyword in the case, the program exits the switch statement.
  4. If no matching case is found, and there’s a “default” case:
    • The code in the “default” case is executed.
  5. If there’s no “break” keyword, all subsequent cases after the matching one will be executed.
  6. Finally, statements after the switch statement are executed.

Break in switch case

The “break” keyword is used to halt the execution inside a switch block. It’s like an emergency exit that allows you to break out of the switchblock. When a “break” statement is encountered, the switch statement terminates, and the program continues to the next line after the switch block.

The “break” statement is not mandatory. If you don’t use it, the program will keep executing the code in subsequent cases, even if they don’t match the initial condition. This behavior is known as “fall-through.”

Example

// 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 define a set of statements that should execute when none of the case conditions match the switch variable.

Using the “default” keyword is optional in a switch case statement. If you omit it and none of the cases match, the program will still run without any issues. It serves as a way to handle situations where none of the defined cases apply.

Important Points About Switch Case Statements

1. Switch expression should result in a constant value

In C and C++, the expression in a switch statement must yield a constant value. Valid expressions include numeric constants, enumerations, and preprocessor macro constants. This constraint ensures that cases can be compared effectively.

// 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 in C/C++ can only evaluate expressions that return values of type int or char, limiting the types of expressions it can handle.

3. Case Values must be Unique

In C, the switch statement does not allow duplicate case values. Each case label must be unique within the same switch block. This ensures that the program can accurately determine which code block to execute based on the switch expression’s value.

4. Nesting of switch Statements

Nesting of switch statements is allowed in C/C++, meaning you can have switch statements inside another switch. However, it’s generally recommended to avoid excessive nesting because it can make the program more complex and harder to read and maintain. It’s often a better practice to refactor the code to make it more understandable and modular when you find the need for nested switch statements.

Examples of switch Statement in C

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


// 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("Thursday");
          break;
      case 6:
          printf("Thursday");
          break;
      case 7:
          printf("Thursday");
          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 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: Switch statements can be more readable than a long series of if-else if statements when dealing with multiple conditions. They provide a cleaner and more structured way to handle branching.
  2. Easier to Debug and Maintain: Switch statements can be easier to debug and maintain, especially when there are many conditions to handle. The code is organized into distinct cases, making it simpler to locate and address issues.
  3. Faster Execution Speed: In some cases, switch statements can lead to faster execution speeds compared to long chains of if-else if statements because the compiler can optimize them more efficiently.

Disadvantages Of C Switch Statement

  1. Limited Data Types: Switch cases can only evaluate expressions of type int or char, which restricts the types of values that can be directly compared within the switch statement.
  2. No Support for Logical Expressions: Unlike if-else statements, switch cases do not support logical expressions. You cannot directly compare complex conditions within a case, which may require additional logic or nesting.
  3. Required “break” Statements: It’s essential to remember to include a “break” statement at the end of each case to prevent fall-through behavior. Forgetting to include “break” can lead to the unintended execution of subsequent cases.

FAQ- Switch Statement in C

Q1. What is a switch statement with an example in C?

Ans. The switch statement in C serves as an alternative to the if-else-if ladder statement. It enables the execution of various operations based on different possible values of a single variable, known as the switch variable. Within the switch statement, you can define distinct sets of statements for different values of the switch variable, making it a structured way to handle multiple cases or conditions.

Q2. What is a switch statement in syntax?

Ans.
The “case” keyword is followed by a constant expression, and it ends with a colon. This expression specifies the value to be matched with the switch expression.
If the value of the switch expression matches the constant expression in a case label, the statements following that case label (until a “break” statement or the end of the switch block) will be executed.
Typically, one or more statements follow a case label to define the actions to be taken when a particular case is matched.

Q3. Is a switch statement a loop?

Ans. A switch statement in C/C++ is not a loop; it’s a conditional control structure used for making decisions based on the value of a switch expression. It’s often likened to an “if-else-if-else” type statement because it allows you to evaluate multiple conditions and execute different blocks of code based on the matching case. While loops are used for repetitive execution, switch statements are used for branching based on specific values.

Hridhya Manoj

Hello, I’m Hridhya Manoj. I’m passionate about technology and its ever-evolving landscape. With a deep love for writing and a curious mind, I enjoy translating complex concepts into understandable, engaging content. Let’s explore the world of tech together

Leave a Comment