Loading lessons...
Nested If
Nested If
An if statement can live inside another if statement. That is a nested if, and it is how you build conditions on top of conditions.
An if inside an if
if (adult) {
if (hasID) {
cout << "Entry allowed" << endl;
}
}
The inner if is only looked at when the outer condition is true. If the outer one is false, the inner question is never even asked.
Braces keep it clear
Always wrap each level in curly braces so the nesting is obvious. Indent the inner if one step deeper than the outer one:
if (service) {
if (age >= 18) {
cout << "Adult service is allowed" << endl;
}
}
Fusing with &&
A common alternative is to merge two checks into a single condition with &&:
if (adult && hasID) {
cout << "Entry allowed" << endl;
}
Both forms work; choose whichever reads easier.
Do not go too deep
Nested conditions get hard to read after a couple of levels. If you find yourself three or four layers down, combine the checks with &&, or refactor into smaller blocks.
TL;DR
- Nested if = an if inside another if.
- The inner if is checked only when the outer condition is true.
- Indent inner blocks so the levels are clear.
- Prefer
&&when you just need the two checks together.