View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Switch Case in C: In-Depth Code Explanation

Updated on 07/04/20258,478 Views

When you start programming in C, you quickly learn that controlling the flow of a program is one of the most important concepts. Also, it’s a common way to make decisions in a C program. Among these, the switch case in C is often favored for handling multiple conditions, especially when the conditions involve comparing the same variable to multiple possible values. 

In addition, where you have to decide between multiple options based on a variable's value, using a switch case in C program can drastically improve the readability of your code. Due to this, every top-tier software development course explores the functionality and utilization of switch case in C. 

Moreover, it’s cleaner, more organized, and often more efficient than using a series of if-else statements, especially when you deal with numerous potential outcomes. So, let’s understand how the switch case in C works, how to implement it effectively, and how it compares to other decision-making structures, like the if-else statement. 

What is a Switch Case in C?

At its core, the switch case in C is a statement that allows you to choose between multiple code blocks to execute based on the value of a single variable. The switch case statement is an alternative to using multiple if-else statements when you are checking the same variable against different constant values or scenarios. 

Why Switch Case in C is Better than Using if-else?

  • Readability: When dealing with multiple values of a single variable, the switch statement can make your code more readable by providing a clear structure.
  • Performance: In many cases, switch statements are more optimized by the compiler, especially when there are many conditions to check. This can improve performance compared to the sequential nature of if-else checks. 

Switch Case Syntax

The syntax of the switch case in C is as follows: 

switch(expression) {
    case constant1:
        // Block of code if expression == constant1
        break;
    case constant2:
        // Block of code if expression == constant2
        break;
    case constant3:
        // Block of code if expression == constant3
        break;
    // More cases as needed
    default:
        // Block of code if expression does not match any case
}
  • expression: This is the value that will be evaluated once by the switch statement. It is typically a variable.
  • case constant: For each case, the value of the expression is compared to the constant. If they match, the corresponding block of code is executed.
  • break: This is an optional statement used to exit the switch block. If omitted, the program continues to execute subsequent case blocks (a feature called "fall-through").
  • default: This is also optional and provides a fallback code block if none of the case conditions are met.

How Does the Switch Case in C Works?

To understand the switch case in detail, let’s break down its functioning step by step:

  1. Expression Evaluation: When a switch case in C is executed, the expression provided in the parentheses is evaluated once. This expression is often a variable or a constant.
  2. Comparison with Case Values: The value of the expression is then compared with the constants in each case block, one by one. The comparison is based on equality (i.e., if the expression value equals the constant in a particular case).
  3. Executing the Matching Case: If a match is found, the code under that case is executed. The program then encounters the break statement (if present), which exits the switch block. If there is no break, the program continues to execute the next case in sequence, regardless of whether it matches or not. This is called "fall-through."
  4. Default Case: If no case matches the expression, the default block is executed (if provided). This acts as a catch-all for unmatched cases.

Flowchart of Switch Case in C

A flowchart is a great way to visualize the flow of control in a program. Here’s how the logic of the switch case can be represented:

Code Examples with Output and Explanation

Now that we have the basics down, let’s see some concrete examples. These examples will help you understand how the switch case works in different scenarios.

Example 1: Simple Switch Case with Integer

Let’s start with a simple example where we compare an integer variable to a set of constants.

#include <stdio.h>

int main() {
    int num = 2;
    switch(num) {
        case 1:
            printf("Number is 1\n");
            break;
        case 2:
            printf("Number is 2\n");
            break;
        default:
            printf("Number is neither 1 nor 2\n");
    }
    return 0;
}

Output:

Number is 2

Explanation:

  • The variable num is set to 2.
  • The switch case in C checks if num matches any of the case values.
  • Since num is 2, it matches case 2 and prints "Number is 2."
  • The break keyword ensures that the program exits the switch statement after the matching block is executed.

Example 2: Using Default Case

In this example, we’ll show what happens when there is no match in the switch statement, and the default case is executed.

#include <stdio.h>

int main() {
    int num = 10;
    switch(num) {
        case 1:
            printf("Number is 1\n");
            break;
        case 2:
            printf("Number is 2\n");
            break;
        default:
            printf("Number is not 1 or 2\n");
    }
    return 0;
}

Output:

Number is not 1 or 2

Explanation:

  • The variable num is set to 10, which doesn't match any of the case values.
  • As a result, the program executes the default case, printing "Number is not 1 or 2."

Example 3: Switch Case with Characters

Let’s take a look at how we can use the switch case in C with characters.

#include <stdio.h>

int main() {
    char grade = 'B';
    switch(grade) {
        case 'A':
            printf("Excellent\n");
            break;
        case 'B':
            printf("Good\n");
            break;
        case 'C':
            printf("Average\n");
            break;
        default:
            printf("Invalid grade\n");
    }
    return 0;
}

Output:

Good

Explanation:

  • The variable grade is set to 'B'.
  • The switch statement checks if grade matches any of the case values.
  • Since grade is 'B', it matches case 'B', and the program prints "Good."

5 Practical Examples Using Switch Case in C

Here are five more practical examples to help you see the versatility of the switch case statement:

  1. Menu-Driven Program:You can use a switch case in C to create a simple menu-driven program where a user selects an option by entering a number. Each option corresponds to a different block of functionality.
  2. Grade Evaluation:In a student grading system, you can use a switch statement to determine the grade category (A, B, C, etc.) based on the student's marks.
  3. Day of the Week:You can assign numbers (1-7) to days of the week (Monday-Sunday) and use a switch statement to print the name of the day based on the input number.
  4. Month Name:A similar application could involve converting a number (1-12) to the corresponding month name using a switch case in C.
  5. Nested Switch Case:You can nest one switch statement inside another to evaluate more complex conditions. For example, checking multiple attributes of an object or user input.

Switch Case in C vs If Else Statement

Let’s break down the differences between switch case and if-else in a more comprehensive way. Here, we’ve provided a brief overview for quick understanding. But, for detailed learning, you can refer to our expert-curated switch case in C vs If Else article. 

Feature

Switch Case in C

If-Else Statement in C

Syntax

Uses case and break keywords

Uses if, else if, and else blocks

Best for

Checking one variable against multiple constant values

Complex conditions, comparisons of different variables

Readability

More readable for multiple values of a single variable

Can get cluttered when there are many conditions

Performance

Typically faster for many conditions, especially with integer values

Slower for multiple conditions since each one is checked sequentially 

Flexibility

Limited to exact values, cannot handle ranges

Very flexible, can handle ranges and complex conditions

Use Case

Ideal when checking multiple values for a single variable (e.g., days of the week, menu options)

Best for handling complex logical conditions involving multiple variables

Conclusion

The switch case in C is an incredibly powerful tool for making decisions in your programs. By providing a clear and structured way to evaluate multiple conditions, it helps you write cleaner, more efficient, and more maintainable code. Whether you are working with numbers, characters, or even more complex conditions, the switch case allows you to streamline your decision-making process.

By understanding the syntax, logic, and real-world applications of the switch case, you can enhance your C programming skills and approach complex problems with ease. Just remember that while the switch statement is often a cleaner and more efficient choice, it isn’t suitable for every situation—so knowing when to use it versus an if-else block will help you make the right decision.

Certainly! Below are 11 new Frequently Asked Questions (FAQs) related to the switch case in C, which expand on concepts not covered earlier in the blog. These FAQs address common challenges, corner cases, and advanced use cases for switch case statements.

FAQs

1. Can a switch case have multiple conditions for the same case?

No, a switch case in C cannot have multiple conditions for the same case. Each case label must be a single constant value or expression. If you need to evaluate multiple conditions that should lead to the same outcome, you can simply stack multiple case labels one after another:

switch (x) {
    case 1:
    case 2:
    case 3:
        printf("x is 1, 2, or 3\n");
        break;
    default:
        printf("x is not 1, 2, or 3\n");
}

This means that if x is 1, 2, or 3, the same code block will execute. There’s no need for multiple conditions; you can combine cases like this.

2. What happens if you forget to include a break statement in a switch case?

If you forget to include a break statement in a switch case, the program will fall through to the next case and execute its code, regardless of whether it matches the expression or not. This is known as "fall-through" behavior.

Example:

switch (x) {
    case 1:
        printf("Case 1\n");
    case 2:
        printf("Case 2\n");
    case 3:
        printf("Case 3\n");
        break;
}

If x is 1, this program will print:

Case 1
Case 2
Case 3

This might not be the intended behavior, so always ensure to add a break unless fall-through is intentional.

3. Can a switch case handle strings or arrays in C?

In C, you cannot directly use strings or arrays as the expression in a switch statement. The switch expression must be an integer, char, or an enumeration type. Since strings are arrays of characters, they are not valid for comparison in a switch.

However, you can achieve similar functionality for strings using a series of if-else statements or by using strcmp to compare string values.

4. Is it possible to have multiple default cases in a switch statement?

No, you cannot have multiple default cases in a single switch statement. A switch statement can only have one default block, which is executed if none of the case conditions match the evaluated expression.

switch (x) {
    case 1:
        printf("One\n");
        break;
    default:
        printf("Default case\n");
        break;
    default:  // Error: Multiple default cases are not allowed
        printf("Another default\n");
}

If you try to add more than one default, the compiler will throw an error.

5. Can a switch case handle ranges of values (e.g., 1-10)?

No, you cannot use ranges or inequalities directly in a switch case. The switch statement compares the expression with a constant value or expression, so ranges are not allowed.

For ranges, you will need to use if-else statements to check whether the value falls within a specific range.

int x = 5;
if (x >= 1 && x <= 10) {
    printf("x is between 1 and 10\n");
} else {
    printf("x is out of range\n");
}

Alternatively, a switch could be used if you break down the ranges into specific values, but for a range, if-else is the most effective approach.

6. Can a switch case handle multiple case statements that evaluate the same code?

Yes, multiple case labels can share the same block of code. If you have several case values that should trigger the same action, you can list them one after another without adding code between them. This is a common use case where you want to check for multiple possibilities and execute the same code.

switch (x) {
    case 1:
    case 2:
    case 3:
        printf("x is 1, 2, or 3\n");
        break;
    default:
        printf("x is not 1, 2, or 3\n");
}

In this example, x can be 1, 2, or 3, and it will print "x is 1, 2, or 3". There’s no need for separate blocks of code for each case.

7. Can switch case statements be nested?

Yes, you can nest switch case statements within one another in C. This is useful when you need to check multiple conditions in a hierarchical manner.

int x = 1, y = 2;
switch (x) {
    case 1:
        switch (y) {
            case 2:
                printf("x is 1 and y is 2\n");
                break;
            default:
                printf("y is not 2\n");
        }
        break;
    default:
        printf("x is not 1\n");
}

In this example, the inner switch evaluates y only when x equals 1.

8. Can the switch statement be used to compare floating-point numbers in C?

No, the switch statement cannot be used with floating-point numbers (like float or double) in C. The expression inside a switch must be an integer, char, or enum.

If you need to compare floating-point values, you must use an if-else statement or a different approach like rounding the floating-point number to a specific precision before comparing.

9. What is the significance of the break keyword in a switch case?

The break keyword in a switch statement serves two purposes:

  1. Exit the Switch Block: It terminates the switch case block, ensuring that no other cases are executed.
  2. Prevent Fall-Through: Without break, if a case matches, the program will continue executing the subsequent cases (even if they don't match). This "fall-through" behavior can sometimes be useful, but it’s often a source of bugs if not intentional.

For example:

switch (x) {
    case 1:
        printf("Case 1\n");
    case 2:
        printf("Case 2\n");
        break;
    case 3:
        printf("Case 3\n");
}

If x is 1, this will print:

Case 1
Case 2

But if break was placed after case 1, it would only print "Case 1".

10. Can a switch case statement be used with enum types in C?

Yes, switch cases can be used with enum types in C. An enum is essentially a set of named integer constants, so the switch statement can evaluate an enum value in the same way it handles integer or character values.

Here’s an example:

enum Day { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday };

int main() {
    enum Day today = Wednesday;

    switch (today) {
        case Monday:
            printf("It's Monday\n");
            break;
        case Wednesday:
            printf("It's Wednesday\n");
            break;
        default:
            printf("Other day\n");
    }
    return 0;
}

In this case, the program would output:

It's Wednesday

11. Is it possible to use expressions (like x + 1) in a switch case?

Yes, expressions can be used in case labels, but they must evaluate to constant values at compile time. You can use expressions such as x + 1, but keep in mind that these expressions need to be constant expressions, which means they must be evaluated during the program's compilation.

int x = 3;
switch (x) {
    case 2 + 1:
        printf("x is 3\n");
        break;
    case 4:
        printf("x is 4\n");
        break;
}

This works because 2 + 1 evaluates to 3, a constant expression, which can be used in a case label.

image

Take a Free C Programming Quiz

Answer quick questions and assess your C programming knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Start Learning For Free

Explore Our Free Software Tutorials and Elevate your Career.

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.