If...Else & Switch

If...Else & Switch in C: A train cannot be in two places at once. When it reaches a set of points, a lever sends it down one track or the other, and once it…

The Analogy: A Railway Points Lever

A train cannot be in two places at once. When it reaches a set of points, a lever sends it down one track or the other, and once it has passed there is no going back to try the alternative.

That is what a conditional does to your program's single line of execution. if is a lever with two positions. A chain of else if is a row of levers, checked in order, where the first one that matches wins and none of the rest are even looked at. switch is a turntable: instead of asking a series of questions, it looks at one number and jumps straight to the matching track.

The ordering property is worth pausing on, because it is where most beginner logic bugs live. In a chain, else if (score >= 70) does not mean "the score is between 70 and 79" — it means "the score is at least 70 and every test above me already failed". The range is implied by position, not stated in the code. Reorder the branches and the meaning quietly changes.


Syntax or Core Structure

#include <stdio.h>

int main(void) {
    int score = 78;

    if (score >= 90) {
        printf("Grade A\n");
    } else if (score >= 80) {
        printf("Grade B\n");
    } else if (score >= 70) {
        printf("Grade C\n");
    } else {
        printf("Grade F\n");
    }

    /* The conditional operator: an if that produces a value. */
    const char *status = (score >= 70) ? "pass" : "fail";
    printf("Status: %s\n", status);

    return 0;
}

Output:

Grade C
Status: pass

The braces are optional when a branch holds exactly one statement. Use them anyway, every time. The most famous bug in this category — Apple's "goto fail" TLS vulnerability of 2014 — was a duplicated indented line under a brace-less if, which therefore always ran.

switch

switch compares one integer expression against a list of compile-time constants and jumps to the match.

#include <stdio.h>

int main(void) {
    char command = 'd';

    switch (command) {
        case 'a':
            printf("adding\n");
            break;
        case 'd':
            printf("deleting\n");
            break;
        case 'l':
        case 'L':                    /* two labels sharing one body */
            printf("listing\n");
            break;
        default:
            printf("unknown command '%c'\n", command);
            break;
    }
    return 0;
}

Output:

deleting

break is not decoration. Without it, execution keeps running straight into the next case, which is called fall-through. Occasionally that is exactly what you want:

int level = 2;

switch (level) {
    case 3: printf("admin\n");    /* falls through */
    case 2: printf("editor\n");   /* falls through */
    case 1: printf("reader\n");
            break;
    default: printf("none\n");
}

Output:

editor
reader

Cumulative permissions like that are the classic legitimate use. Every other fall-through is a missing break, so comment the deliberate ones — modern compilers will warn about the rest under -Wimplicit-fallthrough.


Technical Depth: What switch Can and Cannot Do

switchif / else if chain
What it testsone integer expression against constantsany expressions at all
Ranges such as 70 to 79not possiblenatural
Stringsnot possibleyes, via strcmp
Floating pointnot allowedyes
Compiled tooften a jump table: one step regardless of case countcomparisons in order, first match wins
Falls throughyes, unless you breaknever
Duplicate valuescompile errorsilently unreachable

The jump-table point is the real reason switch exists. A 60-case switch on small integers can compile to a single indexed jump, whereas a 60-branch if chain averages 30 comparisons. For dispatching on an opcode, a state, or a menu choice, switch is both faster and clearer.

Its limits are strict, though. Case labels must be integer constant expressions — case 3: and case 'x': and case MAX: where MAX is a #define or an enum are all fine; case n: where n is a variable is not, and neither is case 1.5: or case "quit":.

Declaring a variable inside a case

A case label cannot be followed directly by a declaration, and any variable you declare is visible to the whole switch body, which is rarely what you want. Wrap the body in braces:

switch (choice) {
    case 1: {
        long amount = read_amount();    /* scoped to these braces */
        deposit(amount);
        break;
    }
    case 2:
        printf("nothing to declare here\n");
        break;
}

The dangling else

An else always attaches to the nearest unmatched if, whatever the indentation suggests.

if (logged_in)
    if (is_admin)
        show_admin_panel();
else                          /* belongs to "if (is_admin)" */
    show_login_page();        /* so this runs for logged-in non-admins */

Braces remove the ambiguity entirely, which is the whole argument for using them unconditionally.

The conditional operator has a type

cond ? a : b produces a single value, so both branches are converted to one common type. flag ? 1 : 2.0 is a double — even when flag is true and the answer is 1. Keep both branches the same type, and keep the whole expression short enough to read on one line.


Real World Example: A Menu Dispatcher

This is the shape of nearly every small command-line tool: read one choice, dispatch on it, validate everything on the way in. Note that money is kept in whole cents, so no floating point is involved and / and % do the formatting.

#include <stdio.h>

static void show_menu(void) {
    printf("1) deposit  2) withdraw  3) balance  0) quit\n> ");
}

int main(void) {
    long balance = 25000;         /* cents */
    int choice = 0;

    show_menu();
    if (scanf("%d", &choice) != 1) {
        printf("Not a number.\n");
        return 1;
    }

    switch (choice) {
        case 1: {
            long amount = 0;
            printf("amount in cents: ");
            if (scanf("%ld", &amount) != 1 || amount <= 0) {
                printf("Invalid amount.\n");
                return 1;
            }
            balance += amount;
            printf("Deposited. Balance %ld.%02ld\n", balance / 100, balance % 100);
            break;
        }
        case 2: {
            long amount = 0;
            printf("amount in cents: ");
            if (scanf("%ld", &amount) != 1 || amount <= 0 || amount > balance) {
                printf("Invalid amount.\n");
                return 1;
            }
            balance -= amount;
            printf("Withdrawn. Balance %ld.%02ld\n", balance / 100, balance % 100);
            break;
        }
        case 3:
            printf("Balance %ld.%02ld\n", balance / 100, balance % 100);
            break;
        case 0:
            printf("Goodbye.\n");
            break;
        default:
            printf("No such option: %d\n", choice);
            break;
    }
    return 0;
}

Output:

1) deposit  2) withdraw  3) balance  0) quit
> 1
amount in cents: 5000
Deposited. Balance 300.00

Three design choices are worth copying. The default case exists, so an unexpected number produces a message rather than silence. Each case that needs a local variable gets its own braces. And every scanf result is checked with || amount <= 0 in the same condition, so a bad read and a nonsensical value are rejected by the same line.


Common Mistakes

  1. Forgetting break. Execution runs on into the next case. This is the single most common switch bug; -Wimplicit-fallthrough catches it.
  2. Writing = instead of ==. if (status = 0) assigns and is always false. Enable -Wall and it becomes a warning you can promote to an error.
  3. Omitting braces. if (x) do_a(); do_b(); always calls do_b(), whatever the indentation implies.
  4. Ordering a chain wrongly. Putting if (score >= 70) before if (score >= 90) makes the A branch unreachable, and nothing warns you.
  5. Ending an if header with a semicolon. if (x); has an empty body, so the block that follows runs unconditionally.
  6. Expecting a range or a string in case. Case labels must be integer constants. Ranges and strcmp need an if chain.
  7. Declaring a variable straight after a case label. It is a syntax error before C23, and the variable would leak into the whole switch. Add braces.
  8. Omitting default. Silently doing nothing for an unexpected value turns a bug into a mystery. Always handle the unknown case, even if you only log it.

Best Practices

  • Brace every branch, including one-line ones. It costs two characters and prevents an entire class of bug.
  • Order an else if chain from the most specific test to the least, and read it back to confirm each branch is reachable.
  • Give switch a default case in every instance, even when you believe the input is already validated.
  • Comment intentional fall-through so a reviewer can tell it apart from a missing break.
  • Reach for switch when you are dispatching on one integer or enum value, and for an if chain when you are testing ranges or several different variables.
  • Keep conditions short by extracting them into named predicates: if (is_valid_amount(amount)) beats a four-clause expression.
  • Use the conditional operator only for a small value choice such as picking one of two strings. If it needs parentheses to be readable, write an if.
  • Prefer positive conditions. if (found) reads better than if (!not_found), and double negatives hide bugs.

Practice Exercises

  1. Grades two ways. Write a program that reads a score from 0 to 100 and prints a letter grade, first with an else if chain and then with a switch on score / 10. Reject scores outside the range, and explain in a comment why the switch version needs the division.
  2. A four-function calculator. Read two doubles and an operator character, then use a switch to compute the result. Handle division by zero without crashing, and make the default case report the offending character.
  3. The fall-through audit. Write a switch on an access level of 1 to 3 that prints cumulative permissions using deliberate fall-through, then write the same behaviour with explicit break statements in every case. Note in a comment which version you would rather maintain and why.