C Switch

The switch statement in C provides a way to execute different blocks of code based on the value of a single variable or expression. It is a control flow statement that offers a more readable and efficient alternative to a series of if-else-if statements when dealing with multiple discrete values.

Key Features

Multiple Cases: Allows for the execution of different blocks of code depending on the value of a variable.

Fall Through: The ability to execute multiple cases in sequence if a break statement is not used.

Default Case: A fallback option when none of the defined cases match the variable's value.

Syntax:

switch (expression) {
case value1:
// Code to execute if expression == value1
break; // Optional, exits the switch block
case value2:
// Code to execute if expression == value2
break; // Optional, exits the switch block
// More cases as needed
default:
// Code to execute if no case matches
}

How It Works

1. Evaluate Expression: The switch expression is evaluated once.

2. Match Cases: The result is compared against each case value sequentially.

3. Execute Code Block: When a match is found, the code associated with that case is executed.

4. Handle Fall Through: If no break is encountered, execution continues with subsequent cases.

5. Default Case: If no matches are found, the default case (if provided) is executed.

Use Cases

Menu Selection: Ideal for handling different user choices in a menu system.

State Machines: Useful for managing different states in a program.

Command Parsing: Effective for executing different commands based on user input or program state.

Valid and Invalid Examples

Valid Switch:

switch (x) { // x is an integer variable
case 1:
// code
break;
case 2:
// code
break;
}

Invalid Switch:

switch (f) { // f is a float variable
case 1.0: // case value must be an integer or character constant
// code
break;
}

Valid Case:

case 'a': // valid case label for a char type

case x + 2: // x + 2 is not a constant expression

Example:

#include <stdio.h>

int main() {
    int day = 6;

    switch (day) {
        case 1:
            printf("Monday\\n");
            break;
        case 2:
            printf("Tuesday\\n");
            break;
        case 3:
            printf("Wednesday\\n");
            break;
        case 4:
            printf("Thursday\\n");
            break;
        case 5:
            printf("Friday\\n");
            break;
        case 6:
            printf("Saturday\\n");
            break;
        case 7:
            printf("Sunday\\n");
            break;
        default:
            printf("Invalid day\\n");
    }

    return 0;
}

Output:

Saturday