0
0
C++programming~5 mins

Switch vs if comparison in C++

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 fixed values to check against one variable.
When you want clearer and simpler code for multiple choices.
When you need to handle different cases quickly and cleanly.
When conditions are simple comparisons like equals.
When you want to avoid writing many if-else statements.
Syntax
C++
switch (variable) {
  case value1:
    // code to run
    break;
  case value2:
    // code to run
    break;
  default:
    // code if no case matches
    break;
}

The switch works only with certain types like integers or characters.

Each case must end with break; to stop running the next cases.

Examples
Switch checks the value of day and runs the matching case.
C++
int day = 3;
switch (day) {
  case 1:
    // Monday
    break;
  case 2:
    // Tuesday
    break;
  case 3:
    // Wednesday
    break;
  default:
    // Other days
    break;
}
If-else checks conditions one by one and runs the first true block.
C++
int number = 10;
if (number == 5) {
  // do something
} else if (number == 10) {
  // do something else
} else {
  // default action
}
Sample Program

This program shows how to assign grades using both switch and if-else. The switch uses integer division to group scores, while if-else checks ranges directly.

C++
#include <iostream>

int main() {
    int score = 85;

    // Using switch
    switch (score / 10) {
        case 10:
        case 9:
            std::cout << "Grade: A\n";
            break;
        case 8:
            std::cout << "Grade: B\n";
            break;
        case 7:
            std::cout << "Grade: C\n";
            break;
        default:
            std::cout << "Grade: F\n";
            break;
    }

    // Using if-else
    if (score >= 90) {
        std::cout << "Grade: A\n";
    } else if (score >= 80) {
        std::cout << "Grade: B\n";
    } else if (score >= 70) {
        std::cout << "Grade: C\n";
    } else {
        std::cout << "Grade: F\n";
    }

    return 0;
}
OutputSuccess
Important Notes

Switch is best for checking one variable against fixed values.

If is more flexible for complex conditions like ranges or multiple variables.

Remember to use break; in switch to avoid running extra cases.

Summary

Switch is simple and clean for many fixed choices.

If works for any condition, including ranges and complex logic.

Choose the one that makes your code easier to read and understand.