top

Search

C Tutorial

.

UpGrad

C Tutorial

Switch Case in C

Programming in any language involves decision-making processes, whether simple or complex. In C programming, we have various constructs for handling these decision-making scenarios. One such important construct is the switch case statement. 

This article aims to provide a deep dive into the concept of switch case statements in C, highlighting its syntax, uses, advantages, disadvantages, and best practices. Keep reading to resolve switch case in C programming questions with efficiency.

Understanding Switch Case Statements

In the world of C programming, a switch case statement is a multiway branch statement that allows us to select one choice among many options. It provides an efficient way to transfer the execution to different parts of code based on the condition or choice.

Writing multiple if-else statements can become quite cumbersome in complex programming scenarios where we need to make decisions based on various conditions. This is where switch case statements come in handy, providing a clean and organised way to handle multiple switch case in C with conditions. 

Syntax of Switch Case Statement

Here's the basic syntax of a switch case statement in C:

switch (n) {
    case label1:
        // code block
        break;

    case label2:
        // code block
        break;

    default:
        // default code block
}

How Does C Switch Statement Work?

The switch statement evaluates the expression inside the parenthesis. The resulting value is then compared with the values of each case. If there's a match, the block of code associated with that case is executed. If none of the case values matches, the default block is executed (if provided).

Flowchart of Switch Case in C

Here's a simple flowchart representation of how a switch case statement works in C:

Evaluate switch(n)
         |
         V
  Case 1 --> Execute case 1 --> Exit
         |
         V
  Case 2 --> Execute case 2 --> Exit
         |
         V
  Default --> Execute default case

Rules of C Switch Statement

A switch case statement in C must follow certain rules to ensure correct and expected functioning. Let's discuss these rules along with some switch case examples.

1. The switch expression must be an integer or character constant.

The switch parenthesis's expression must be evaluated with an integer or a character. You cannot use float, double, or other data types in the switch expression.

Example:

int x = 2;
switch (x) {
    case 1:
        printf("One");
        break;
    case 2:
        printf("Two");
        break;
    default:
        printf("None");
}

In this example, x is an integer type variable. Hence, it's a valid expression to use within the switch statement.

2. Case labels must be unique and must be compile-time constants.

Each case in a switch statement must have a unique, constant value. Variable or changeable values are not allowed as case labels.

Example:

#define MAX 10
int x = 5;

switch (x) {
    case 1:
        printf("One");
        break;
    case MAX:
        printf("Ten");
        break;
    default:
        printf("None");
}

Here, MAX is a #define constant. Hence, it's a valid case label.

3. The default case is optional and can be used when no case matches.

You don't always have to use a default case. However, it's often a good idea to include one to handle situations where none of the case labels matches the switch expression.

Example:

int x = 20;

switch (x) {
    case 10:
        printf("Ten");
        break;
    case 15:
        printf("Fifteen");
        break;
    default:
        printf("None");
}

In this case, since x is 20, none of the case labels matches. Therefore, the default case is executed.

4. The break statement is optional but often necessary.

The break statement is used to exit a switch case block. If omitted, the program will continue executing the next case, even if it doesn't match the switch expression. This is known as a fall-through.

Example:

int x = 1;

switch (x) {
    case 1:
        printf("One");
        // break is omitted here
    case 2:
        printf("Two");
        break;
    default:
        printf("None");
}

In this case, although x is 1, the program prints both "One" and "Two". This is because of the fall-through due to the missing break statement.

Remember, these rules aren't optional. Violating these rules might lead to compilation errors or unexpected behaviour in your program.

Why do we Need a C Switch Case?

Switch case statements allow for better readability and simplicity in handling multiple conditions. They provide an efficient alternative to lengthy if-else chains and are especially useful when dealing with enumerated types.

Important Points to C Switch Case

Here are some of the important points to keep in mind regarding the C Switch Case: 

  1. The break keyword is used to end the current case. Without it, the program will continue executing the next case.

  2. The default case is executed when no other cases match.

  3. The default case doesn't necessarily need to be at the end, but it's a common practice to place it there for better readability.

Format of Switch Case Statements

The standard format of switch case statements involves:

  • switch keyword

  • a test expression/variable in parenthesis

  • case labels followed by colon (:)

  • statements to be executed

  • break statement

  • default case, if required

Examples of Simple Switch Case Statements

Let's understand with an easy switch case example:

#include <stdio.h>

int main() {
    int month = 3;

    switch(month) {
        case 1:
            printf("January");
            break;
        case 2:
            printf("February");
            break;
        case 3:
            printf("March");
            break;
        default:
            printf("Invalid month");
    }

    return 0;
}

In this program, the switch statement checks the month variable. If the month is 1, it will print "January". If the month is 2, it will print "February", and so on. If no cases match, the default case will be executed, and it will print "Invalid Month".

Explanation of the Break Statement

The break statement is used to exit from the switch case statement. If we do not use the break statement, all cases after the correct case are executed until a break is encountered or the program reaches the end of the switch block.

Switch Case vs. If Else

The switch case and if-else statements in C are both control flow constructs that let us perform different actions based on different conditions. Despite their similarities, they have fundamental differences in handling conditions, syntax, and efficiency in specific scenarios.

Readability and Syntax

A switch case in C with multiple values is cleaner and more organised based on a single variable or expression. On the other hand, multiple if-else statements can become quite cumbersome and less readable as the number of conditions increases.

Switch Case Example:

int x = 2;

switch (x) {
    case 1:
        printf("One");
        break;
    case 2:
        printf("Two");
        break;
    default:
        printf("None");
}

If-Else Equivalent:

int x = 2;

if (x == 1) {
    printf("One");
} else if (x == 2) {
    printf("Two");
} else {
    printf("None");
}

In these examples, the switch case statement is more compact and easier to read than the equivalent if-else statements.

Versatility

if-else statements are more versatile than switch case statements. While switch case statements can only test a single variable or expression against different values, if-else statements can handle complex conditions with different variables and logical operators.

If-Else Example:

int x = 2;
int y = 3;

if (x == 1 && y == 2) {
    printf("Condition 1");
} else if (x == 2 || y == 3) {
    printf("Condition 2");
} else {
    printf("None");
}

The above code would not be possible to represent with a switch case statement because it involves logical operators and checks conditions based on multiple variables.

Efficiency

A switch case statement can sometimes be more efficient than equivalent if-else statements. The compiler can optimise switch case statements using a technique known as a jump table, which allows for faster execution. However, in most cases, the performance difference is negligible and shouldn't be a determining factor in choosing between the two.

Default Conditions

Both switch case and if-else statements support default conditions, executed when no other condition matches. In switch case statements, this is done using the default case. In if-else statements, this is done using the final else block.

Switch Case Statements: Advantages and Disadvantages

Switch case statements, like all programming constructs, have their strengths and weaknesses. Understanding these advantages and disadvantages will help you determine when it's best to use switch case statements and when other options, like if-else statements, might be a better fit.

Advantages

Disadvantages

Enhances code readability and organisation

Only supports integer and character data types

Faster execution due to compiler optimisation using jump table

Comparison operators aren't supported

Simplifies complex if-else chains

Cases can fall through if not terminated with a break

Ideal for menu-driven programming and multiple choice scenarios

A variable or expression can't be used as a case constant

The advantages of switch case statements shine when you have a single variable or expression leading to multiple outcomes. However, its limitations in data type support, inability to use comparison operators, and potential for case fall-through are important considerations.

Use Cases for Switch Case Statements

Switch case statements can be incredibly useful in a variety of programming situations. Let's explore some of the common use cases.

1. Menu-Driven Programs:

Switch case is commonly used for creating menu-driven programs, where a user's choice can lead to different parts of the code. It provides a simple and elegant solution to execute different blocks of code based on user input.

int choice;

printf("Enter your choice: 1. Pizza, 2. Burger, 3. Pasta\n");
scanf("%d", &choice);

switch (choice) {
    case 1:
        printf("You chose Pizza");
        break;
    case 2:
        printf("You chose Burger");
        break;
    case 3:
        printf("You chose Pasta");
        break;
    default:
        printf("Invalid choice");
}

2. State Machine Logic:

Switch case statements can represent state machine logic very cleanly. For example, using a switch case statement, you can represent different states of a game (loading, running, paused, game over, etc.).

enum GameState {LOADING, RUNNING, PAUSED, GAME_OVER};
enum GameState state = LOADING;

switch (state) {
    case LOADING:
        printf("Game is loading...");
        break;
    case RUNNING:
        printf("Game is running");
        break;
    case PAUSED:
        printf("Game is paused");
        break;
    case GAME_OVER:
        printf("Game over");
        break;
}

3. Multiple Choices Scenarios:

Whenever you have multiple choices based on a single variable or expression, a switch case statement can be an efficient solution. It's far cleaner and more organised than using a series of if-else statements.

char vegetable= 'C';

switch (vegetable) {
    case 'A':
        printf("Acorn");
        break;
    case 'B':
        printf("Bell Pepper");
        break;
    case 'C':
        printf("Chives");
        break;
    case 'D':
        printf("Dill");
        break;
    default:
        printf("Invalid vegetable");
}

Multiple Case Labels

In a switch case statement, we can have multiple case labels. This means we can have the same code for multiple cases.

switch (n) {
    case 1:
    case 2:
    case 3:
        printf("n is between 1 and 3");
        break;
    default:
        printf("n is not between 1 and 3");
}

Default Case

The default case in a switch case statement is executed when no case values match with the switch expression. It's optional but can be useful in handling unexpected cases.

switch (n) {
    case 1:
        printf("n is 1");
        break;
    default:
        printf("n is not 1");
}

Nested Switch Case

We can also use switch case statements inside another switch case statement. This is called a nested switch case statement.

switch (n) {
    case 1:
        switch(x) {
            case 'a':
                printf("n is 1 and x is a");
                break;
        }
        break;
    default:
        printf("n is not 1");
}

Best Practices

  1. Always use the break statement to prevent case fall-through.

  2. Use default cases to handle unexpected cases.

  3. Keep your cases simple and use nested switch case statements sparingly, as they can become difficult to read and maintain.

Conclusion

Mastering the switch case statement in C is a crucial step in your journey to becoming a proficient C programmer. It is a powerful construct that can significantly simplify your code when dealing with multiple conditions. Remember the syntax, use cases, advantages, and best practices we've discussed here to use the switch case statement effectively in your C programming journey.

Interested in enhancing your programming skills? Check out upGrad’s comprehensive Executive PG Program in Data Science to strengthen your programming skills as well as nurture a successful career in the expanding field of data science!

FAQs

1. When should I use a switch case statement instead of an if-else statement?

If you have a single variable or expression that can lead to multiple outcomes, a switch case statement can be more efficient and readable than a series of if-else statements.

2. What happens if I forget to use the break statement in a switch case statement?

If you forget to use the break statement in a switch case statement, the program will continue executing the next case, even if it doesn't match the condition. This is known as a case fall-through.

3. Can I use a switch case statement with float data types in C?

No, switch case statements in C can only be used with integer and character data types. It does not support floating point or double data types.

4. What is a nested switch case statement?

A nested switch case statement refers to a switch case statement inside another switch case statement. It's useful when dealing with complex decision-making scenarios but should be used sparingly as it can become difficult to read and maintain.

Leave a Reply

Your email address will not be published. Required fields are marked *