C Switch Statement

The switch statement chooses one block from many options, based on the value of a variable. It is cleaner than a long if else ladder when you compare one variable with fixed values.

Syntax

switch (expression) {
    case value1:
        // code
        break;
    case value2:
        // code
        break;
    default:
        // code if nothing matches
}

Example: day name

#include <stdio.h>

int main(void) {
    int day = 3;

    switch (day) {
        case 1: printf("Monday\n"); break;
        case 2: printf("Tuesday\n"); break;
        case 3: printf("Wednesday\n"); break;
        default: printf("Other day\n");
    }
    return 0;
}

Output:

Output of the above program is

Wednesday

Without break (fall through)

If you forget break, the program continues to the next case also.

#include <stdio.h>

int main(void) {
    int n = 1;

    switch (n) {
        case 1: printf("One\n");
        case 2: printf("Two\n");
        case 3: printf("Three\n"); break;
        default: printf("Other\n");
    }
    return 0;
}

Output:

Output of the above program is

One
Two
Three

Sometimes fall through is useful. Many cases can share one block:

#include <stdio.h>

int main(void) {
    char ch = 'e';

    switch (ch) {
        case 'a': case 'e': case 'i': case 'o': case 'u':
            printf("Vowel\n");
            break;
        default:
            printf("Consonant\n");
    }
    return 0;
}

Output:

Output of the above program is

Vowel

Rules

  • The expression must be an integer or a character. You cannot use float or string.
  • Case values must be constants and cannot repeat.
  • default is optional and can be written at any place, but is usually last.
Note: Use break after every case, unless you want the fall through on purpose.

Next: C While Loop.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
Write a C program to check whether a number is even or odd
Write a C program to check whether a user is eligible to vote or not
Write a C program to check whether an alphabet is vowel or consonant
Write a C program to find the maximum number between three numbers
Write a C program to check whether a number is positive, negative or zero
Write a C program to calculate an electricity bill
Write a C program to print 1 to 10 numbers using a while loop
Interview Questions & Answers
What is the difference between while and do while loop in C?
What is the difference between break and continue in C?
How to check if a number is prime in C?
How to find the factorial of a number in C?