C++ Conditions and Boolean Logic
Translate rules into readable if statements, compound Boolean expressions, and switch branches while keeping boundary behavior explicit.
Before this lesson
Write mutually exclusive branches
Combine range and state checks safely
Choose if or switch from the shape of the rule
The short answer
Conditions choose a path from Boolean facts. Build and name the smallest facts, order branches so only the intended path can run, and test values on both sides of every important boundary.
If selects a path
An if statement evaluates a condition and executes its body when the condition is true. An else provides the alternative. An else if chain models mutually exclusive categories: after one branch runs, later branches are skipped.
Keep the condition close to the decision it controls. Parsing, validation, and the domain decision can be separate facts even when a short guard combines them for an early exit.
#include <iostream>
int main()
{
int temperature{31};
if (temperature >= 35)
{
std::cout << "Extreme heat\n";
}
else if (temperature >= 25)
{
std::cout << "Warm\n";
}
else
{
std::cout << "Cool\n";
}
}Branch order defines behavior
Overlapping comparisons make order meaningful. In a descending threshold chain, first match the highest category. In an ascending chain, test the lowest first. Write sample boundary values before code so the intended inclusivity is explicit.
Prefer early rejection for invalid states. After if (!valid) return 1;, the main path can assume the validated contract and avoid another level of indentation.
Name compound facts
A long condition can hide its own meaning. Break age >= 18 && has_id && !is_suspended into named Boolean facts when each concept matters. Short-circuit logic safely avoids later operations when an earlier guard fails.
| Rule | Expression | Boundary test |
|---|---|---|
| Inside inclusive range | value >= low && value <= high | low - 1, low, high, high + 1 |
| Outside range | value < low || value > high | Same four values |
| Required and allowed | has_token && is_enabled | All four truth combinations |
| Safe division | denominator != 0 && total / denominator > limit | Zero and nonzero divisor |
Switch handles discrete choices
switch is useful when one integral or enum value selects among named alternatives. Each case must finish deliberately, commonly with break or return, unless fallthrough is explicit. Always consider a default path for unexpected external values.
Use if for ranges and unrelated Boolean facts. Use switch for one discrete selector. The choice should expose the rule rather than minimize line count.
Quick knowledge check
Answer before you reveal.
01Why must the grade chain check 90 before 80?
A score of 95 satisfies both comparisons, so the more specific higher boundary must claim it first in an else-if chain.
02Does a valid integer parse prove the score is valid?
No. Parsing checks representation; a separate rule checks the range.
Exercise
Practice challenge
Read a score from 0 through 100, reject values outside that range, and print A, B, C, D, or F using an ordered branch chain.
Requirements
- Scores below 0 and above 100 are rejected
- Every valid score produces exactly one grade
- Boundary values 59 60 69 70 89 and 90 are tested
Optional extension: Extract the grade decision into a function in lesson 7.
Open in C++ compilerLesson checkpoint
One small step locks it in
Mark this lesson complete, then keep the momentum going.
Clear up the details
Frequently asked questions
Are braces optional for one statement?
Sometimes, but consistent braces reduce mistakes when a branch later gains another statement.
When is a ternary expression appropriate?
It is useful for one compact value choice. Prefer an if statement when branches perform several actions or need explanation.
Can switch use std::string directly?
No. A traditional switch selects integral or enum-like values; use if comparisons or map text to a discrete command first.