Home C switch statement in C tutorial

switch statement in C tutorial

The switch statement in C is used to execute one of many code blocks based on the value of a given expression.

It’s particularly useful when you have multiple conditions to check for a single variable and want to avoid a long chain of if-else statements.

1. Syntax of the switch Statement

switch (expression) {
    case constant1:
        // Code to execute if expression equals constant1
        break;
    case constant2:
        // Code to execute if expression equals constant2
        break;
    // Add more cases as needed
    default:
        // Code to execute if none of the cases match
}
  • expression: This is the variable or expression being checked. It must evaluate to an integer or character value.
  • case constant: A value that is compared against expression. If it matches, the code inside this case is executed.
  • break: Ends the current case and exits the switch statement. Without break, execution falls through to the next case.
  • default: This code block runs if no other cases match the expression (similar to the else block in if-else statements).

2. Basic Example of switch

Let’s start with a simple example using the switch statement to print a message based on a day number.

#include <stdio.h>

int main() {
    int day = 3;

    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;
}

Explanation:

  • The value of day is 3, so the code for case 3 executes and prints “Wednesday”.
  • The break statement prevents the program from running subsequent cases.

Output:

Wednesday

3. Using switch with char Values

The switch statement can also work with char values. Here’s an example that prints a message based on a grade.

#include <stdio.h>

int main() {
    char grade = 'B';

    switch (grade) {
        case 'A':
            printf("Excellent!\n");
            break;
        case 'B':
            printf("Good job!\n");
            break;
        case 'C':
            printf("Fair.\n");
            break;
        case 'D':
            printf("Needs improvement.\n");
            break;
        case 'F':
            printf("Failed.\n");
            break;
        default:
            printf("Invalid grade.\n");
    }

    return 0;
}

Explanation:

  • The value of grade is ‘B’, so the code for case ‘B’ executes, printing “Good job!”.

Output:

Good job!

4. Fall-Through Behavior in switch

If you omit the break statement, C will “fall through” to the next case, executing all subsequent cases until it encounters a break.

#include <stdio.h>

int main() {
    int score = 2;

    switch (score) {
        case 1:
            printf("Low score\n");
        case 2:
            printf("Medium score\n");
        case 3:
            printf("High score\n");
        default:
            printf("Unknown score\n");
    }

    return 0;
}

Explanation:

  • Since there is no break statement after case 2, both Medium score, High score, and Unknown score are printed.
  • This “fall-through” behavior can be intentional in some cases, but be cautious as it can lead to unintended consequences if break is omitted accidentally.

Output:

Medium score
High score
Unknown score

5. Using switch with default

The default case is optional and runs if none of the specified cases match. It acts like the else statement in an if-else chain.

#include <stdio.h>

int main() {
    int number = 10;

    switch (number) {
        case 1:
            printf("Number is 1\n");
            break;
        case 5:
            printf("Number is 5\n");
            break;
        default:
            printf("Number is not 1 or 5\n");
    }

    return 0;
}

Explanation:

  • Since number is 10 and doesn’t match any case, the default block executes, printing “Number is not 1 or 5”.

Output:

Number is not 1 or 5

6. switch with Multiple Cases for the Same Outcome

You can use multiple case labels for the same code block if they share the same outcome.

#include <stdio.h>

int main() {
    char letter = 'A';

    switch (letter) {
        case 'A':
        case 'a':
            printf("The letter is A or a.\n");
            break;
        case 'B':
        case 'b':
            printf("The letter is B or b.\n");
            break;
        default:
            printf("The letter is not A or B.\n");
    }

    return 0;
}

Explanation:

  • Both case ‘A’ and case ‘a’ execute the same code block, making the switch case insensitive for ‘A’.

Output:

The letter is A or a.

7. switch with Enum Values

The switch statement can also be used with enum types. This is especially useful in applications where you define a set of constant values.

#include <stdio.h>

enum Direction { UP, DOWN, LEFT, RIGHT };

int main() {
    enum Direction dir = LEFT;

    switch (dir) {
        case UP:
            printf("Moving up\n");
            break;
        case DOWN:
            printf("Moving down\n");
            break;
        case LEFT:
            printf("Moving left\n");
            break;
        case RIGHT:
            printf("Moving right\n");
            break;
        default:
            printf("Invalid direction\n");
    }

    return 0;
}

Explanation:

  • The value of dir is LEFT, so the case LEFT code block executes, printing “Moving left”.

Output:

Moving left

8. switch Statement to Perform Arithmetic Operations

The switch statement can be used in a calculator program to perform basic arithmetic operations.

#include <stdio.h>

int main() {
    int num1 = 10, num2 = 5;
    char op = '+';

    switch (op) {
        case '+':
            printf("Result: %d\n", num1 + num2);
            break;
        case '-':
            printf("Result: %d\n", num1 - num2);
            break;
        case '*':
            printf("Result: %d\n", num1 * num2);
            break;
        case '/':
            if (num2 != 0) {
                printf("Result: %d\n", num1 / num2);
            } else {
                printf("Error: Division by zero\n");
            }
            break;
        default:
            printf("Invalid operator\n");
    }

    return 0;
}

Explanation:

  • The operator op is +, so the case ‘+’ code block executes, printing the result of num1 + num2.

Output:

Result: 15

9. Nested switch Statements

You can nest switch statements, although this is rarely needed. Here’s an example:

#include <stdio.h>

int main() {
    int category = 1;
    int item = 2;

    switch (category) {
        case 1:
            printf("Category 1\n");
            switch (item) {
                case 1:
                    printf("Item 1.1\n");
                    break;
                case 2:
                    printf("Item 1.2\n");
                    break;
                default:
                    printf("Unknown item\n");
            }
            break;
        case 2:
            printf("Category 2\n");
            break;
        default:
            printf("Unknown category\n");
    }

    return 0;
}

Explanation:

  • The outer switch checks category, and if it’s 1, the inner switch checks item.
  • item is 2, so “Item 1.2” is printed.

Output:

Category 1
Item 1.2

10. Summary Table of switch Examples

Use Case Description Example Code
Basic switch Executes code based on integer value switch (day) { case 1: … case 2: … }
Using char values Executes code based on char value switch (grade) { case ‘A’: … case ‘B’: … }
Fall-through behavior Executes multiple cases without break case 1: … case 2: …
Default case Handles unmatched cases default: printf(“Unknown”);
Multiple cases for one code Groups cases with the same outcome case ‘A’: case ‘a’: printf(“A”);
Enum values Uses enums for clarity in case labels switch (dir) { case UP: … case DOWN: … }
Arithmetic operations Uses switch for basic calculator switch (op) { case ‘+’: … case ‘-‘: … }
Nested switch Contains a switch within another switch switch (cat) { case 1: switch (item) { … } }

Complete Example: Menu-Driven Program Using switch

This program uses a switch statement to implement a simple menu.

#include <stdio.h>

int main() {
    int choice;

    printf("Menu:\n");
    printf("1. Add\n");
    printf("2. Subtract\n");
    printf("3. Multiply\n");
    printf("4. Divide\n");
    printf("Enter your choice (1-4): ");
    scanf("%d", &choice);

    int a = 10, b = 5;

    switch (choice) {
        case 1:
            printf("Addition: %d\n", a + b);
            break;
        case 2:
            printf("Subtraction: %d\n", a - b);
            break;
        case 3:
            printf("Multiplication: %d\n", a * b);
            break;
        case 4:
            if (b != 0) {
                printf("Division: %d\n", a / b);
            } else {
                printf("Error: Division by zero\n");
            }
            break;
        default:
            printf("Invalid choice\n");
    }

    return 0;
}

Explanation:

  • This program displays a menu with options for arithmetic operations.
  • The user selects an option, and the corresponding operation is executed using a switch statement.

Sample Output:

Menu:
1. Add
2. Subtract
3. Multiply
4. Divide
Enter your choice (1-4): 3
Multiplication: 50

The switch statement in C provides a structured and efficient way to handle multiple conditions, making your code more readable and maintainable.

You may also like