Let your program make decisions: comparison and logical operators, if-else chains, switch and the ternary operator.
A program does not always run the same lines in order; it has to choose a path based on the data. Warn if the battery voltage is low, skip the division if the resistance is zero, run the operation chosen from a menu. All of these are written with conditional statements.
Comparison and logical operators
| Operator | Meaning |
|---|---|
== != | equal, not equal |
< <= > >= | less than, less than or equal, greater than, greater than or equal |
&& | and (both are true) |
|| | or (at least one is true) |
! | not |
if, else if, else
Let's print the charge state of a single-cell Li-ion battery based on its voltage:
#include <iostream>
int main() {
double voltage = 3.9;
if (voltage >= 4.1) {
std::cout << "Full\n";
} else if (voltage >= 3.7) {
std::cout << "Good\n";
} else if (voltage >= 3.3) {
std::cout << "Low\n";
} else {
std::cout << "Critical\n";
}
// Combined condition: safe operating range
if (voltage > 3.0 && voltage < 4.2) {
std::cout << "In range\n";
}
// Ternary operator
const char* action = (voltage >= 3.7) ? "continue" : "charge";
std::cout << "Decision: " << action << '\n';
// switch: menu choice
int choice = 2;
switch (choice) {
case 1:
std::cout << "First\n";
break;
case 2:
std::cout << "Second\n";
break;
case 3:
std::cout << "Third\n";
break;
default:
std::cout << "Invalid\n";
break;
}
return 0;
}
Good
In range
Decision: continue
Second
The chain is evaluated from top to bottom, and the first true branch runs; the rest are not even checked. Since 3.9 is less than 4.1, the first branch is skipped and the second branch (>= 3.7) turns out true. Notice that the order matters: if you list the thresholds from smallest to largest, the first condition will always be true.
When to use switch?
switch compares a single integer (or character, or enum) value against constant values. It is ideal for menu choices, state machines and command codes. Don't forget to write break at the end of each case; if you don't, the program "falls through" into the case below as well. This is sometimes done on purpose, but it is usually a bug. The default branch runs when no case matches.
switch does not work with decimal numbers or text; for those you use an if chain.
The ternary operator
The form condition ? a : b produces a if the condition is true and b otherwise. It is neat for short assignments; once you start nesting it, it becomes unreadable, so write an if instead.
C++17: an initializer inside if
Since C++17 you can declare a variable inside an if and test it right away. The variable lives only in this if block:
if (int err = readErrorCode(); err != 0) {
std::cout << "Error code: " << err << '\n';
}
Here readErrorCode is a function left up to you; the example is only meant to show the syntax.
The classic trap: writing if (x = 5). This is not a comparison but an assignment; x becomes 5 and the condition always counts as true. Use a double equals sign for comparison: if (x == 5). The -Wall flag usually shows this mistake as a warning.
Don't compare decimal numbers with ==. The expression 0.1 + 0.2 == 0.3 is false because these numbers cannot be stored exactly in binary. Instead, check whether the difference is smaller than a small tolerance: std::abs(a - b) < 1e-9 (requires the <cmath> header).
Try it yourself
- Write an if-else chain that prints "Cold" (<10), "Mild" (10-25) and "Hot" (>25) for a temperature value.
- Write a menu program: 1 = current, 2 = power, 3 = exit. Handle the choice with
switch. - On your own, add an "error if the resistance is zero" check to the Ohm calculator from the previous lesson.
// Mini quiz
Click an option; you will see right away, with the reason, whether it is correct or not.
Mark it when you finish: your progress is saved and you earn +20 XP.
Tip: ← → keys let you move between lessons.