Switch Statement


In C programming, a switch statement is a control flow statement that allows you to select among multiple alternatives based on the value of a given expression. It provides a more concise way to handle multiple conditions compared to using a series of if-else statements.

The general syntax of a switch statement in C programming is as follows:

Syntax

switch (expression) {
   case value1:
     // Code executed if 'expression' equals 'value1'
       break;
   case value2:
     // Code executed if 'expression' equals 'value2'
       break;
    // More cases can be added as needed.
    // The default case is optional.
    default:
       // Code for unmatched cases.
}


Hereโ€™s, how the switch statement works?

  1. We evaluate the expression and it should evaluate to an integral or character type (e.g., int, char, enum).

  2. The expression compares its value with each case value (value1, value2, etc.).

  3. If the expression matches any of the case values, the code block following that case label executes. The switch statement terminates when it encounters the break statement, allowing the program to continue executing after the switch block.

  4. If the expression does not match any of the case values, the code block under the default label (if provided) executes. The default case is optional and serves as a fallback when no other case matches the value of the expression.

  5. If there is no matching case and no default case, the switch statement will do nothing, and the program flow will continue to the next line of code after the switch block.

For instance:

#include <stdio.h>
int main() {
  int choice;

  printf("Enter a number between 1 and 3: ");
  scanf("%d", &choice);

  switch (choice) {
      case 1:
        printf("You chose option 1.\n");
        break;
      case 2:
        printf("You chose option 2.\n");
        break;
      case 3:
        printf("You chose option 3.\n");
        break;
      default:
        printf("Invalid choice. Pick a number from 1 and 3.\n");
    }

    return 0;
}


Hereโ€™s, how it works:

  1. The main() function is the entry point, and it return type of int, indicating that the function will return an integer value.

  2. Inside the main() function, a variable choice of type int is declared. This variable will store the userโ€™s input.

  3. The program uses printf() to prompt the user for a number between 1 and 3, and then uses scanf() to read and store the userโ€™s input in the variable choice.

  4. After reading the userโ€™s input, the program enters the switch statement:
    • If the value of choice is 1, the program executes the code block under case 1, which prints โ€œYou chose option 1.โ€ and then breakโ€™s out of the switch statement. The break statement is crucial here; otherwise, the program would continue executing the code for other cases as well.

    • If the value of choice is 2, the program executes the code block under case 2, which prints โ€œYou chose option 2.โ€ and then breakโ€™s out of the switch statement.

    • If the value of choice is 3, the program executes the code block under case 3, which prints โ€œYou chose option 3.โ€ and then breakโ€™s out of the switch statement.

    • If the value of choice doesnโ€™t match any of the cases above (i.e., itโ€™s not 1, 2, or 3), the program executes the code block under the default label. It prints โ€œInvalid choice. Pick a number from 1 and 3.โ€

  5. After executing the appropriate case or the default case, the program reaches the return 0; statement. This statement exits the main() function and returns 0 to the operating system, indicating successful execution of the program.
Output
Enter a number between 1 and 3: 1
You chose option 1.

The program prompts the user for a number. It then uses a switch statement to display a corresponding message based on the input (1, 2, or 3). If the input is any other number, an error message is shown. Finally, after executing the switch statement, the program terminates and returns 0.


Use cases

Certainly! In various applications, C programming commonly utilizes switch statements to simplify code and enhance efficiency when handling multiple possible cases.

Here are a few common use cases for switch statements:

  1. Menu-driven Programs:
    Menu-driven programs often use switch statements, where the user has a set of options, and the program performs different actions depending on the userโ€™s choice. The switch statement allows you to easily handle different menu options and execute corresponding code blocks.
  2. Handling Enumerations:
    In C, users define enumerations as data types to specify named constants. Switch statements can efficiently handle enumerations, making the code more readable and self-explanatory.
  3. Error Handling:
    Switch statements can handle error codes or error conditions returned from functions. Based on the error code, the program can take appropriate actions to recover from the error or display relevant error messages to the user.
  4. State Machines:
    Switch statements play a vital role in implementing state machines, which model the behavior of systems with discrete states and their transitions. Developers represent each state as a case and manage the transitions using the break statement.
  5. Processing Command-Line Arguments:
    When building command-line tools, developers can use switch statements to process various command-line arguments, each directing to a specific action.
  6. Calculator Programs:
    Simple calculator programs can use switch statements to handle various arithmetic operations like addition, subtraction, multiplication, division, etc., depending on the userโ€™s choice.

Switch statements in C programming offer a structured and efficient approach for handling multiple cases. As a result, they enhance code readability and maintainability. Moreover, they serve as a vital tool for controlling program flow based on expression values.