Lesson 52 +10 XP

Nested if Statements

Nested if Statements

You can put an if inside another if. That's a nested if, useful when a second condition only matters after the first.

The pattern

int x = 5;
int y = 10;
if (x > 0) {
    if (y > 5) {
        printf("x is positive and y is big");
    }
}

Output: x is positive and y is big

When is it useful?

When the inner check is only meaningful if the outer one already passed. For example: "if the user is logged in, then check their permissions".

Careful: the dangling else

An else attaches to the nearest unmatched if. Braces keep you safe.

TL;DR

  • An if inside an if is called nested.
  • The inner condition only runs if the outer one is true.
  • Else attaches to the nearest unmatched if - use braces.