Conditional Statements
Conditional statements let a program make decisions, running different code depending on whether an expression evaluates to true or false.
if, else if, and else
An if statement runs a block only when its condition is true. Chaining else if lets you check multiple conditions in order, and a final else catches anything not matched above.
int mark = 74;
if (mark >= 80) {
std::cout << "Distinction" << std::endl;
} else if (mark >= 60) {
std::cout << "Merit" << std::endl;
} else if (mark >= 50) {
std::cout << "Pass" << std::endl;
} else {
std::cout << "Fail" << std::endl;
}
The switch Statement
A switch is a clean alternative to a long else if chain when you are comparing one variable against several exact values. Each case must end with break;, or execution will fall through into the next case.
int day = 3;
switch (day) {
case 1: std::cout << "Monday"; break;
case 2: std::cout << "Tuesday"; break;
case 3: std::cout << "Wednesday"; break;
default: std::cout << "Invalid day";
}
Common Mistakes
- Forgetting
break;in a switch case, causing execution to fall through into the next case. - Using
=instead of==inside anifcondition, which assigns instead of compares. - Writing conditions that overlap so an earlier
else ifalways matches first, making later branches unreachable. - Using a switch on a type it does not support, such as a
std::string(switch only works on integral and enum types).
Professional Tip
Order your else if conditions from most specific to least specific. In the grading example, checking >= 80 first is essential — reversing the order would let a distinction mark match a lower bracket instead.
Your Turn
Write a program that asks for a month number (1-12) and uses a switch statement to print the season it falls in (Summer, Autumn, Winter, Spring), including a default case for invalid input.
Mini Quiz
What happens if you forget the break statement in a switch case?
break;, C++ continues executing the statements in the next case, regardless of whether its condition matches. This is called fall-through.