Nested if statements refine a decision in stages.

nested branch An inner `if` only runs after the outer condition has chosen that path.
classification Multiple checks can turn one numeric value into a label.

Nested If

score
nested_if.c
Replay: real traced execution (multi-file project)
#include <stdio.h>

int main(void) {
    int score = 82;
    const char *label = "unknown";

    if (score >= 60) {
        if (score >= 90) {
            label = "honors";
        } else {
            label = "pass";
        }
    } else {
        label = "retry";
    }

    printf("%s:%d\n", label, score);
    return 0;
}
#include <stdio.h>

int main(void) {
    int score = 45;
    const char *label = "unknown";

    if (score >= 60) {
        if (score >= 90) {
            label = "honors";
        } else {
            label = "pass";
        }
    } else {
        label = "retry";
    }

    printf("%s:%d\n", label, score);
    return 0;
}
#include <stdio.h>

int main(void) {
    int score = 96;
    const char *label = "unknown";

    if (score >= 60) {
        if (score >= 90) {
            label = "honors";
        } else {
            label = "pass";
        }
    } else {
        label = "retry";
    }

    printf("%s:%d\n", label, score);
    return 0;
}
  1. score ← 82, label ← unknown

    3int main(void) {4    int score→ 82 = 82; //@score=45, 965    const char *label→ unknown = "unknown";
  2. if (score >= 60)

    7if (score82 >= 60) {8    if (score >= 90) {
  3. label ← pass

    9    label = "honors";10} else {11    label→ pass = "pass";12}
  4. printf("%s:%d ", label, score);

    17    printf("%s:%d\n", labelpass, score82);18    return 0;19}
    outputpass:82
  1. score ← 45, label ← unknown

    3int main(void) {4    int score→ 45 = 45;5    const char *label→ unknown = "unknown";
  2. label ← retry

    12    }13} else {14    label→ retry = "retry";15}
  3. printf("%s:%d ", label, score);

    17    printf("%s:%d\n", labelretry, score45);18    return 0;19}
    outputretry:45
  1. score ← 96, label ← unknown

    3int main(void) {4    int score→ 96 = 96;5    const char *label→ unknown = "unknown";
  2. if (score >= 60)

    7if (score96 >= 60) {8    if (score >= 90) {
  3. label ← honors

    7if (score >= 60) {8    if (score96 >= 90) {9        label→ honors = "honors";10    } else {
  4. printf("%s:%d ", label, score);

    17    printf("%s:%d\n", labelhonors, score96);18    return 0;19}
    outputhonors:96

Follow the Branches

  1. score starts as 82.
  2. The outer check score >= 60 is true.
  3. The inner check score >= 90 is false.
  4. The inner else sets label to pass.
  5. The program prints pass:82. | score | outer check | inner check | label | | --- | --- | --- | --- | | 82 | true | false | pass | | 45 | false | not reached | retry | | 96 | true | true | honors |

Exercise: nested_if.c

Reproduce pass:82, then use the pinned score variants 45 and 96 to predict retry:45 and honors:96.