Skip to main content

Compare switch and if-else-if ladder

Short answer

if‑else‑if ladder evaluates arbitrary conditions sequentially, can use ranges and floats, while switch tests an integer/char expression for equality with constants, jumping directly to the matching case. switch is faster and more readable for many discrete choices, but requires break to avoid fall‑through.

Compare if-else-if ladder and switch construct with example (and flowchart).

Both select one block out of many. The if-else-if ladder tests conditions one after another; switch compares one expression against constant case values.

if-else-if ladderswitch
Can test any condition, including ranges and logical expressionsTests only equality of one integer or character expression with constants
Works with float and string comparisonsWorks with int and char only
Conditions are evaluated one by one from the topJumps directly to the matching case
The last else handles the defaultdefault handles the unmatched case
No break neededbreak needed to avoid fall-through
Slower for many choicesFaster and more readable for many choices

if-else-if ladder example

#include <stdio.h>
int main(void)
{
    int marks = 72;
    if (marks >= 80)      printf("Distinction\n");
    else if (marks >= 60) printf("First division\n");
    else if (marks >= 45) printf("Second division\n");
    else if (marks >= 32) printf("Pass\n");
    else                  printf("Fail\n");
    return 0;
}

Output: First division

switch example

#include <stdio.h>
int main(void)
{
    float a, b;
    char op;
    scanf("%f %c %f", &a, &op, &b);
    switch (op)
    {
        case '+': printf("%.2f\n", a + b); break;
        case '-': printf("%.2f\n", a - b); break;
        case '*': printf("%.2f\n", a * b); break;
        case '/':
            if (b != 0) printf("%.2f\n", a / b);
            else printf("Division by zero\n");
            break;
        default:  printf("Invalid operator\n");
    }
    return 0;
}

For input 12 * 4, output: 48.00

Flowchart of switch

        < expression >
        /    |     \
   case 1  case 2  default
     |       |        |
  [stmt1] [stmt2]  [stmt3]
  [break] [break]     |
     \       |       /
      \      |      /
       next statement

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 5 questions →