Dr. Roger Ianjamasimanana

C switch case statement syntax

By Dr. Roger Ianjamasimanana

The switch statement in C provides a way to execute different parts of code based on the value of an expression. It enhances code readability and efficiency, especially when dealing with multiple conditions.

1. Basic syntax of the switch case statement

The switch statement evaluates an expression and executes the corresponding case block that matches the expression’s value.

switch (expression) {
    case constant1:
        // code to execute if expression == constant1
        break;
    case constant2:
        // code to execute if expression == constant2
        break;
    // more cases...
    default:
        // code to execute if no case matches
}

Example

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

2. How does the switch case statement work?

The switch statement evaluates the expression once and compares it with each case. If a match is found, the corresponding block of code is executed until a break statement is encountered or the switch ends.

Role of the break statement

The break statement terminates the switch block, preventing the execution from falling through to subsequent cases.

switch (value) {
    case 1:
        // code
        break;
    case 2:
        // code
        break;
    default:
        // code
}

3. Using default case

The default case is optional and is executed if none of the specified case values match the expression. It acts as a fallback mechanism.

Example with the default statement:

#include <stdio.h>

int main() {
    char grade;

    // Prompt user for input
    printf("Enter your grade (A, B, C, D, F): ");
    fflush(stdout);
    scanf(" %c", &grade); // Note the space before %c to consume any leftover whitespace

    // Using switch statement to evaluate the grade
    switch (grade) {
        case 'A':
        case 'a':
            printf("Excellent!\n");
            break;
        case 'B':
        case 'b':
        case 'C':
        case 'c':
            printf("Well done\n");
            break;
        case 'D':
        case 'd':
            printf("You passed\n");
            break;
        case 'F':
        case 'f':
            printf("Better try again\n");
            break;
        default:
            printf("Invalid grade\n");
    }

    return 0;
}

4. Multiple cases with the same outcome

Multiple case labels can share the same block of code, allowing for cleaner and more efficient code when different values require the same action.

#include <stdio.h>
#include <ctype.h> // For tolower function

int main() {
    char ch;

    // Prompt  the user for an input
    printf("Enter a single alphabet character: ");
    fflush(stdout);
    scanf(" %c", &ch); // The space before %c ignores any leading whitespace

    // Convert the character to lowercase to handle both cases
    ch = tolower(ch);

    // Using switch statement to check for vowels
    switch (ch) {
        case 'a':
        case 'e':
        case 'i':
        case 'o':
        case 'u':
            printf("Vowel\n");
            break;
        default:
            // Check if the character is an alphabet
            if ((ch >= 'a' && ch <= 'z')) {
                printf("Consonant\n");
            } else {
                printf("Invalid input. Please enter an alphabet character.\n");
            }
    }

    return 0;
}

5. Common mistakes

Missing break statements

Forgetting to include break can cause unintended fall-through, leading to multiple cases being executed.

#include <stdio.h>

int main() {
    int value;

    // Prompt user for input
    printf("Enter a number (1-2): ");
    fflush(stdout);
    scanf("%d", &value);
   
    // Using switch statement
    printf("\nUsing switch:\n");
    switch (value) {
        case 1:
            printf("One\n");
            // Intentional fall-through: no break here
        case 2:
            printf("Two\n");
            break;
        default:
            printf("Other\n");
    }

    return 0;
}

Output when value is 1:

One
Two

Non-integral types

The switch statement only works with integral types (e.g., int, char). Using non-integral types like float or double will result in a compilation error.

6. Best practices

  • Always use a break: prevents accidental fall-through by terminating each case with a break statement.
  • Use default case: handles unexpected values and enhances code robustness.
  • Keep cases simple: each case should handle a single responsibility to maintain readability.
  • Order cases logically: group related cases together for better organization.

7. When to use switch vs. if-else?

Use switch when you have multiple discrete values to compare against a single expression. It is often more readable and efficient than multiple if-else statements in such scenarios.

Example comparison:

Using if-else:

#include <stdio.h>

int main() {
    int day;

    // Prompt user for input
    printf("Enter day number (1-3): ");
    fflush(stdout);
    scanf("%d", &day);

    // Using if-else
    printf("\nUsing if-else:\n");
    if (day == 1) {
        printf("Monday\n");
    } else if (day == 2) {
        printf("Tuesday\n");
    } else if (day == 3) {
        printf("Wednesday\n");
    } else {
        printf("Invalid day\n");
    }
    return 0;
}

Using switch:

#include <stdio.h>

int main() {
    int day;

    // Prompt user for input
    printf("Enter day number (1-3): ");
    fflush(stdout);
    scanf("%d", &day);

    // Using switch
    printf("\nUsing switch:\n");
    switch (day) {
        case 1:
            printf("Monday\n");
            break;
        case 2:
            printf("Tuesday\n");
            break;
        case 3:
            printf("Wednesday\n");
            break;
        default:
            printf("Invalid day\n");
    }

    return 0;
}

8. Advanced use of switch case statement: fall-through behavior

What is a fall-through behavior? Fall-through behavior in C’s switch statements occurs when, after executing a matching case block, the program continues to execute subsequent case blocks without encountering a break statement. This means that once a case is matched, all code following it runs sequentially until a break, return, or the end of the switch is reached.

Intentional fall-through can be used when multiple cases share common code. However, it should be used sparingly and documented clearly to avoid confusion.

#include <stdio.h>

int main() {
    int level;

    // Prompt user for input
    printf("Enter level number (1-2): ");
    fflush(stdout);
    scanf("%d", &level);

    // Using switch statement to evaluate the level
    switch (level) {
        case 1:
            printf("Level 1\n");
            // Intentional fall-through: no break here
        case 2:
            printf("Level 2\n");
            break;
        default:
            printf("Unknown level\n");
    }

    return 0;
}

Example output

If level is 1:

Level 1
Level 2

If level is 2:


Level 2

feature-top
Readers’ comment
feature-top
Log in to add a comment
🔐 Access