Lesson 55 +10 XP

switch vs if/else

switch vs if/else

Both switch and if/else make decisions. Which one should you pick?

switch shines for exact matches

When comparing one integer/char against many exact values, switch is tidy:

char grade = 'B';
switch (grade) {
    case 'A':
        printf("Excellent!");
        break;
    case 'B':
        printf("Good job.");
        break;
    default:
        printf("Keep trying.");
}

if/else shines for ranges and complex logic

Comparisons like x > 100, ranges, or combinations need if:

int score = 150;
if (score > 100) {
    printf("New record!");
} else {
    printf("Keep going.");
}

Rule of thumb

  • Exact value match on one variable -> switch.
  • Ranges, comparisons, or logic -> if/else.

TL;DR

  • switch = many exact matches on one value.
  • if/else = ranges, comparisons, and complex conditions.
  • Both work; pick the one that reads more clearly.