Switch Case

Switch Case

The switch statement in C is a control flow statement used for decision-making. It provides an efficient way to choose between multiple alternatives based on the value of an expression.

Here’s the basic syntax of the switch statement:

switch (expression) {
    case constant1:
        // code block 1
        break;
    case constant2:
        // code block 2
        break;
    // add more cases as needed
    default:
        // code block for default case
        break;
}
  • expression: This is the value that the switch statement evaluates. It can be of integral type (char, int, long) or an enumeration.
  • case constant1, case constant2, …: These are the possible values that the expression can take. If the expression matches one of these constants, the corresponding code block following that case label will be executed.
  • break: The break statement is used to terminate the switch statement and exit the switch block. If break is omitted, control will fall through to the next case.
  • default: This is an optional case label that is used when none of the other cases match the value of the expression. It’s similar to the else clause in an if-else statement.

Here’s an example of using the switch statement:

#include <stdio.h>

int main() {
    int choice = 2;
    
    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\n");
            break;
    }

    return 0;
}

Output:

You chose option 2

    Leave a Reply

    Your email address will not be published.

    Need Help?