C++ Nested If
Sometimes one decision depends on another. You can place an if statement inside another if statement to handle these layered situations. This is called a nested if, and it lets you check a second condition only after the first one has passed.
A nested if is simply an if (or if...else) statement written inside the body of another if or else block. The inner condition is only tested when the outer condition is true, so you can express step by step logic.
An if inside an if
#include <iostream>
using namespace std;
int main() {
int age = 25;
bool hasLicense = true;
if (age >= 18) {
if (hasLicense) {
cout << "You are allowed to drive.\n";
} else {
cout << "You are old enough, but need a license.\n";
}
} else {
cout << "You are too young to drive.\n";
}
return 0;
}Note: The inner if only runs because the outer condition (age >= 18) was true. If the outer condition is false, C++ never even looks at the inner block.
Reading nested logic
Think of nested ifs as questions inside questions. First C++ asks the outer question. Only if the answer is yes does it move on to ask the inner question. Careful indentation makes this flow easy to follow.
Deciding a ticket price
#include <iostream>
using namespace std;
int main() {
int age = 12;
bool isMember = false;
if (age < 13) {
if (isMember) {
cout << "Child member: free entry.\n";
} else {
cout << "Child: half price ticket.\n";
}
} else {
cout << "Adult: full price ticket.\n";
}
return 0;
}Tips for keeping nesting readable
- Indent each level so the structure is visible at a glance.
- Avoid nesting too deeply. More than two or three levels becomes hard to read.
- When conditions can be combined, use logical operators like && instead of extra nesting.
- Always match every opening curly brace with a closing one.
Note: The two examples above could also be written with the && operator, such as if (age >= 18 && hasLicense). Nesting is useful when the inner and outer cases need different messages, but combining conditions is often cleaner when they do not.