Switch Statement in C





The "switch" statement is used in C programming to select one of many code blocks to be executed based on the value of a given expression.

When you have multiple cases to consider based on the value of a single expression, the "switch" statement provides a more concise alternative to using multiple "if-else" statements. It allows you to specify different code blocks to execute for each possible value of the expression.

The expression within the "switch" statement is evaluated, and its value is compared to the values specified in "case" labels. If a match is found, the corresponding code block is executed. If no match is found, an optional "default" label can be used to specify a code block that executes when none of the "case" values match.

The switch statement promotes efficient execution by performing direct value matching instead of evaluating multiple conditions. It can be particularly useful when dealing with enumerated types, menu options, state machines, or any situation where a single expression needs to be compared against multiple possibilities.

Syntax

The syntax of the "switch" statement is as follows:

    switch (expression) {
      case value1:
        // code to execute if expression matches value1
        break;
        
      case value2:
        // code to execute if expression matches value2
        break;
        
      // more cases can be added
      
      default:
        // code to execute if none of the cases match
    }
  


The switch statement evaluates the expression once and then matches its value to one of the constants specified in the cases. The expression is usually an integer or a character, although it can also be an enumeration or a single-value floating-point variable.

When the switch statement is executed, the expression is evaluated, and the resulting value is compared against each case constant. If a match is found, the corresponding code block is executed, starting from that case's label until a break statement is encountered or the switch statement ends.

If no match is found, the code in the default block (if present) is executed. The default block serves as a catch-all when none of the case constants match the evaluated expression.

It's important to note that after executing the code block associated with a case, the program "falls through" to the subsequent cases unless a break statement is encountered. This behavior allows multiple cases to share the same code block, providing a way to handle multiple matching values in a single section of code.

Working Principle of the Switch Statement in C


The switch statement in C works based on the following principles:

  1. The switch statement begins by evaluating an expression or variable to determine its value.
  2. The value of the expression is then compared against the values specified in the case labels.
  3. If a match is found between the expression value and a case label, the corresponding code block associated with that case is executed.
  4. After executing the code block for a matched case, the switch statement continues executing the subsequent code blocks until a break statement is encountered or until the end of the switch statement.
  5. The break statement is used to exit the switch statement and prevents the execution of subsequent code blocks. It transfers control to the statement immediately following the switch statement.
  6. If none of the case labels match the expression value, the code block associated with the optional default label (if present) is executed. The default label acts as a catch-all for unmatched values.
  7. Once the code block for a matched case or the default case (if no match) is executed, the switch statement completes its execution and the program continues with the next statement after the switch statement.


Example

Let's consider an example where we determine the day of the week based on a given number:

    #include <stdio.h>

    int main() {
      int day;
      printf("Enter a number (1-7): ");
      scanf("%d", &day);
      
      switch (day) {
        case 1:
          printf("Sunday\n");
          break;
          
        case 2:
          printf("Monday\n");
          break;
          
        case 3:
          printf("Tuesday\n");
          break;
          
        case 4:
          printf("Wednesday\n");
          break;
          
        case 5:
          printf("Thursday\n");
          break;
          
        case 6:
          printf("Friday\n");
          break;
          
        case 7:
          printf("Saturday\n");
          break;
          
        default:
          printf("Invalid day\n");
      }
      
      return 0;
    }
  
Output:
Enter a number (1-7): 1
Sunday
Enter a number (1-7): 5
Thursday
Enter a number (1-7): 8
Invalid day

In this example, the program asks the user to enter a number between 1 and 7. The program then uses the "switch" statement to determine the corresponding day of the week based on the number.

Each "case" represents a possible value of the expression. If the value matches one of the "case" labels, the corresponding day of the week is printed. If none of the cases match, the "default" code block is executed, printing "Invalid day".

By using the "switch" statement, you can simplify the decision-making process when dealing with multiple cases based on a single expression in your C programs.



Important Points on Switch Statement in C

  1. The switch statement is a control flow statement that selects one of many code blocks to execute based on the value of a given expression.
  2. The expression within the switch statement is typically an integral type (e.g., int or char) or an enumeration constant.
  3. The switch statement evaluates the expression and compares its value against the values specified in the case labels.
  4. Each case label represents a specific value that the expression is compared to. When a match is found, the corresponding code block is executed.
  5. After executing a code block associated with a case label, the switch statement continues executing subsequent code blocks unless a break statement is encountered. The break statement exits the switch statement.
  6. If none of the case labels match the expression's value, the code block associated with the optional default label is executed.
  7. Multiple case labels can be associated with the same code block using "fallthrough" by omitting the break statement.
  8. The default label serves as a catch-all for values that do not have a specific case.
  9. The switch statement provides a concise alternative to using multiple if-else statements when considering many possible values.
  10. Ensure that each case label and the default label are unique within the switch statement to avoid unexpected behavior.


Comparison of the Switch Statement with if-else Statements in C:


Switch Statement

The switch statement is a control flow statement in C that allows you to select one of many code blocks to be executed based on the value of a given expression.

Here's the general syntax of the switch statement:

    
      switch (expression) {
        case constant1:
          // Code to be executed if expression matches constant1
          break;
        case constant2:
          // Code to be executed if expression matches constant2
          break;
        // more cases...
        default:
          // Code to be executed if expression doesn't match any of the constants
      }
    
  

The switch statement evaluates the expression and then matches its value to one of the constants specified in the cases. If a match is found, the corresponding code block is executed. If no match is found, the code in the default block (if present) is executed.

if-else Statements

if-else statements in C provide another way to control the flow of code based on certain conditions. They allow you to execute different code blocks depending on whether a condition is true or false.

Here's the general syntax of an if-else statement:

    
      if (condition1) {
        // Code to be executed if condition1 is true
      } else if (condition2) {
        // Code to be executed if condition1 is false and condition2 is true
      } else {
        // Code to be executed if both condition1 and condition2 are false
      }
    
  

The if-else statement evaluates the conditions one by one, and the code block associated with the first true condition is executed. If none of the conditions are true, the code in the else block (if present) is executed.

Comparison

Both the switch statement and if-else statements provide ways to make decisions and control the flow of code based on conditions. However, there are some differences between them:

  • The switch statement is typically used when there are multiple conditions to check against a single variable, whereas if-else statements are used when there are different conditions to evaluate independently.
  • The switch statement can only compare the expression against constant values, whereas if-else statements can evaluate any Boolean expression.
  • Switch statements are generally more efficient than if-else statements when there are many cases to compare, as the expression is evaluated only once.
  • If-else statements offer more flexibility as they can handle complex conditions and can include logical operators (e.g., &&, ||) to combine multiple conditions.

It's important to choose the appropriate construct based on the specific requirements of your program.



if you don't have break in case it will execute next all case statements until it gets break

    
#include<stdio.h>
        
int main()
{
int exp;
printf("Enter the option:\n");
scanf("%d", &exp);
        
switch(exp)
{
case 1: printf("Case-1 Is Going To Execute.\n");
// if you don't have break it will execute next statement 
case 2: printf("Case-2 Is Going To Execute.\n"); break;
case 3: printf("Case-3 Is Going To Execute.\n"); break;
default:
printf("Note A Valid Option.");
}
        
return 0;
}
Enter the option :
1
Case-1 Is Going To Execute.
Case-2 Is Going To Execute.
Enter the option :
2
Case-2 is going to execute.

Switch Statement with Expression

This program demonstrates the usage of a switch statement with an expression in C.

-- In C, the expression within the switch statement can be a variable or any valid expression.
-- The value of the expression is evaluated, and the program flow jumps to the matching case label.

#include<stdio.h>
        
int main()
{
int num = 10;
        
switch (num % 3)
{
case 0:
printf("The number is divisible by 3.");
break;
case 1:
printf("The number leaves a remainder of 1 when divided by 3.");
break;
case 2:
printf("The number leaves a remainder of 2 when divided by 3.");
break;
default:
printf("Invalid number.");
}
        
return 0;
}
The number leaves a remainder of 1 when divided by 3.


Switch Statement with Right Shift Operator

This program demonstrates the usage of a switch statement with the right shift operator in C.

-- The right shift operator (>>) shifts the bits of a number to the right.
-- In this program, we use the right shift operator to manipulate the switch expression.

#include<stdio.h>
        
int main()
{
int number = 15;
            
switch (number >> 2)
{
case 0:
printf("The number is zero");
break;
case 1:
printf("The number is one");
break;
case 2:
printf("The number is two.");
break;
default:
printf("Invalid number range.");
}
        
return 0;
}

Step 1: Binary Representation of 15


        15 = 0000 1111
    

Step 2: Right Shifting by 2 Positions


        0000 1111 >> 2
    

Step 3: Shifting the Bits to the Right


        0000 0011
    

Step 4: Decimal Conversion


        0000 0011 = 3
    

Therefore, the expression 15 >> 2 evaluates to 3.

Invalid number range.


Pass the case value as character :

#include <stdio.h>

int main() {
    char character;

    // Read the character from the form data
    scanf("%c", &character);

    switch (character) {
        case 'a':
        case 'e':
        case 'i':
        case 'o':
        case 'u':
        case 'A':
        case 'E':
        case 'I':
        case 'O':
        case 'U':
            printf("The character '%c' is a vowel.\n", character);
            break;

        default:
            printf("The character '%c' is a consonant.\n", character);
            break;
    }

    return 0;
}
output:
Enter a charactor :A
The character 'A' is a vowel.
Enter a charactor :G
The character 'G' is a consonant.
Here's an example of a calculator program implemented using a switch statement in C:
#include <stdio.h>

int main() {
    char op;
    double num1, num2, result;

    printf("Enter an operator (+, -, *, /): ");
    scanf("%c", &op);

    printf("Enter two numbers: \n");
    scanf("%lf %lf", &num1, &num2);

    switch (op) {
        case '+':
            result = num1 + num2;
            printf("Sum: %.2lf\n", result);
            break;

        case '-':
            result = num1 - num2;
            printf("Difference: %.2lf\n", result);
            break;

        case '*':
            result = num1 * num2;
            printf("Product: %.2lf\n", result);
            break;

        case '/':
            if (num2 != 0) {
                result = num1 / num2;
                printf("Quotient: %.2lf\n", result);
            } else {
                printf("Error: Division by zero is not allowed.\n");
            }
            break;

        default:
            printf("Error: Invalid operator.\n");
    }

    return 0;
}
output:
Enter an operator (+, -, *, /): +
Enter two numbers:
5
6
Sum: 11.00