Skip to content

Beginner · Operators and control flow · topic 8 of 60 · 25 min

Decisions: if, else and switch

Explanation

if runs code when a condition is non-zero; else if and else cover the other cases. switch jumps to the case matching an integer or char value; each case needs break, or execution falls through into the next. The ternary operator chooses between two values. Beware if (x = 5), which assigns instead of comparing.

if, else if, else

c
int units = 250;
double rate;
if (units <= 100) {
    rate = 3.0;
} else if (units <= 300) {
    rate = 5.0;
} else {
    rate = 7.5;
}
printf("Rate: %.1f\n", rate);   // Rate: 5.0
Only the first matching branch runs. (Sample slab rates for practice.)

The = versus == bug

c
int x = 3;
if (x = 5) {                 /* assigns 5 to x; the value 5 is non-zero → always true */
    printf("x is 5\n");      /* always printed, and x is now 5! */
}
if (x == 5) { … }            /* the comparison you meant */
Careful: if (x = 5) compiles in C, because assignment is an expression. gcc -Wall warns "suggest parentheses around assignment used as truth value". Some programmers write constants first (if (5 == x)) so a missing = becomes a compile error. Also beware a stray semicolon: if (x > 0); { … } makes the block run always.

Braces and the dangling else

Without braces an if controls only the next statement, and an else belongs to the nearest unmatched if, whatever the indentation says. Always use braces; many safety standards (such as MISRA C, module 9) require them.

The ternary operator

c
int qty = 1;
printf("%d %s\n", qty, qty == 1 ? "item" : "items");
int fee = (amount >= 499) ? 0 : 40;

switch

c
char grade = 'B';
switch (grade) {
    case 'A':
        printf("Excellent\n");
        break;
    case 'B':
    case 'C':                       /* grouped: B and C share this code */
        printf("Good\n");
        break;
    case 'D':
        printf("Pass\n");
        break;
    default:
        printf("Invalid grade\n");
}

switch works on integer types (int, char, enum values). Case labels must be constant expressions; you cannot use strings or ranges in standard C. Without break, execution falls through into the following cases. If you fall through on purpose, write a comment such as /* fall through */ (gcc's -Wimplicit-fallthrough, part of -Wextra, recognises it; C23 adds the [[fallthrough]]; attribute).

c
int n = 1;
switch (n) {
    case 1: printf("one ");
    case 2: printf("two ");      /* no break above: falls through */
    default: printf("other");
}
/* prints: one two other */
Think of it like this: switch with fall-through is like a row of shops where the doors between shops are open: you enter at your shop (case) and keep walking through every following shop unless a wall (break) stops you.
Tip: Always include a default case, even if it only reports an error. It catches values you did not expect, such as a corrupted status code from a file.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Decisions: if, else and switch · 1/6

if and switch

In this lesson your C programs will make decisions.

Prefer a video by a teacher? Find free videos on “c if else switch case break fall through tutorial” on YouTube ↗

In real life: An ATM menu

A simple ATM simulator reads a menu choice as an int and uses switch to run the right action, with default for invalid choices. Real ATM software is far bigger, but menus like this are common in embedded and kiosk devices.

c
int choice = 2;
switch (choice) {
    case 1: printf("Balance: Rs 12,500\n"); break;
    case 2: printf("Enter amount to withdraw\n"); break;
    case 3: printf("Mini statement printing…\n"); break;
    default: printf("Invalid option\n");
}

Practice (0/3 done)

Task 1 · Question

What does this print? int n = 2; switch (n) { case 1: printf("A"); case 2: printf("B"); case 3: printf("C"); break; default: printf("D"); }

Task 2 · Question

What does this print? int x = 0; if (x = 0) printf("zero"); else printf("non-zero");

Task 3 · Practice

Write a program that reads a month number (1–12) and a year, and prints the number of days, using switch with grouped cases for 31- and 30-day months and a leap-year check for February (divisible by 4 and not by 100, or divisible by 400). Print "Invalid month" for other numbers.

Quick quiz

Question 1

1.Which types can a standard C switch use?

Question 2

2.What happens without break at the end of a case?

Question 3

3.What does gcc -Wall warn about in if (a = b)?

Question 4

4.int a = 7; printf("%s", a % 2 ? "odd" : "even"); prints…

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

Which types can a standard C switch use?

Answer: Integer types like int, char and enums

Case labels must be integer constants.

What happens without break at the end of a case?

Answer: Execution falls through to the next case

That is fall-through.

What does gcc -Wall warn about in if (a = b)?

Answer: An assignment used as a condition

It suggests parentheses or ==.

int a = 7; printf("%s", a % 2 ? "odd" : "even"); prints…

Answer: odd

7 % 2 is 1 (true).

How many branches of if / else if / else can run?Related

Answer: At most one

Only the first true branch runs.

From Decisions: if, else and the ternary

let x; switch (1) { case 1: x = 'one'; case 2: x = 'two'; break; } What is x?Related

Answer: 'two'

There is no break after case 1, so it falls through and case 2 sets x to two.

From switch, the ternary operator and lookup tables

A switch case has code but no break. What happens?Related

Answer: Compile error: control cannot fall through

C# does not allow fall-through from a non-empty case (error CS0163).

From Decisions: if, else, switch and switch expressions

Which type can NOT be used in a switch?Related

Answer: std::string

switch needs an integral or enum value. Use if / else if for strings.

From Operators and decisions: if, else and switch

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 2 more topics in “Operators and control flow” before its exam: Loops: for, while and do-while, Solving problems with loops.
  2. Module 2 exam: Operators and control flow · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Functions and arrays. 60 topics left in the course before the final exam.

← Previous: Type conversion and casting