0
0
Cprogramming~5 mins

Switch vs if comparison

Choose your learning style9 modes available
Introduction

We use switch and if to make decisions in code. They help the program choose what to do based on different conditions.

When you have many choices based on one variable's value.
When you want clearer code for multiple fixed options.
When you need to check ranges or complex conditions, if is better.
When you want faster decision making for many fixed cases, switch can be faster.
When you want to handle different commands or menu options.
Syntax
C
switch (variable) {
    case value1:
        // code to run
        break;
    case value2:
        // code to run
        break;
    default:
        // code if no case matches
        break;
}

// vs

if (condition1) {
    // code to run
} else if (condition2) {
    // code to run
} else {
    // code if no condition matches
}

switch works only with fixed values like numbers or characters.

if can check any condition, like ranges or multiple variables.

Examples
This switch prints the day name for 1 or 2, otherwise prints "Other day".
C
switch (day) {
    case 1:
        printf("Monday\n");
        break;
    case 2:
        printf("Tuesday\n");
        break;
    default:
        printf("Other day\n");
        break;
}
This if checks score ranges and prints grades.
C
if (score >= 90) {
    printf("Grade A\n");
} else if (score >= 80) {
    printf("Grade B\n");
} else {
    printf("Grade C or below\n");
}
Sample Program

This program shows how switch and if can do the same decision based on the variable option.

C
#include <stdio.h>

int main() {
    int option = 2;

    // Using switch
    switch (option) {
        case 1:
            printf("You chose option 1\n");
            break;
        case 2:
            printf("You chose option 2\n");
            break;
        default:
            printf("Unknown option\n");
            break;
    }

    // Using if
    if (option == 1) {
        printf("You chose option 1\n");
    } else if (option == 2) {
        printf("You chose option 2\n");
    } else {
        printf("Unknown option\n");
    }

    return 0;
}
OutputSuccess
Important Notes

Remember to use break; in switch to stop checking other cases.

if can handle more complex checks than switch.

switch is often easier to read when checking one variable against many values.

Summary

switch is good for many fixed value checks on one variable.

if is more flexible for complex or range conditions.

Both help your program decide what to do next.