Beginner · Operators and control flow · topic 8 of 60 · 25 min
Decisions: if, else and switch
Explanation
if, else if, else
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.0The = versus == bug
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 */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
int qty = 1;
printf("%d %s\n", qty, qty == 1 ? "item" : "items");
int fee = (amount >= 499) ? 0 : 40;switch
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).
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 */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
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.
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)
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"); }
What does this print? int x = 0; if (x = 0) printf("zero"); else printf("non-zero");
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
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Loops: for, while and do-whileOperators and control flow · same module
- Decisions: if, else and the ternaryJava Programming (Core to Spring Boot) · Control flow and methods
- switch, the ternary operator and lookup tablesJavaScript Programming (language in depth) · Strings, decisions and loops
- Decisions: if, else, switch and switch expressionsC# and .NET · Decisions, loops and methods
- Operators and decisions: if, else and switchC++ Programming (modern C++ and DSA) · Decisions, loops and functions
- Decisions with if and switchGo Programming (backend and cloud) · Control flow and functions
Questions people ask about this
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
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.
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).
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.
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
- 2 more topics in “Operators and control flow” before its exam: Loops: for, while and do-while, Solving problems with loops.
- Module 2 exam: Operators and control flow · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Functions and arrays. 60 topics left in the course before the final exam.