C++
Nested conditionals
Learn to build complex logic with nested if and switch.
Nested if
When a condition is meaningful only if another condition is also true, you use a nested if. You write a second if inside the outer if's block; the inner condition is then evaluated only when the outer one is true.
For example: if (age >= 18) { if (hasLicense) { std::cout << "Can drive"; } }. Here hasLicense is checked only when age is 18 or above. Nested if can hurt readability; combining with logical operators is a good alternative.
if inside switch
switch and if can be used together. When you want a case to produce different output based on another condition, you place an if inside the case body. This combines a categorical choice with a sub-condition.
For example, in switch (role) { case 1: if (active) { ... } break; } special code runs only when role is 1 and active is true. Indentation and short blocks help keep nested structures readable.
Exercise Compute the letter grade
The score variable is set to 85. With if (score >= 90) set grade to "A", with else if (score >= 80) to "B", and with else to "C"; then print it with std::cout. The output must be B.
Show example solution
#include <iostream>
#include <string>
int main() {
int score = 85;
std::string grade;
if (score >= 90) {
grade = "A";
} else if (score >= 80) {
grade = "B";
} else {
grade = "C";
}
std::cout << grade << std::endl;
return 0;
}
Test yourself
-
In a nested if, what happens when the outer condition is false?
if (outer) {
if (inner) { ... }
}
- The inner condition is skipped
- The inner condition still runs
- The program crashes
- An infinite loop forms
Show answer
The inner condition is skipped — When the outer condition is false none of the inner block runs.
-
Write the nested if condition
bool hasLicense = true;
if (age >= 18) {
if (____) { std::cout << "Can drive"; }
}
Show answer
bool hasLicense = true;
if (age >= 18) {
if (hasLicense) { std::cout << "Can drive"; }
}
-
Match each construct to its scenario
- if (a) { if (b) { ... } }
- Both conditions needed
- switch (x) { case 1: if (y) { ... } }
- Sub-condition in a case
- if (a) { ... } else { ... }
- Two-way choice
- switch (x) { default: ... }
- Catch-all case
Next lesson: Summary - Conditionals