What is Nested If Programs in C- Free Embedded C Programming Course

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

PREV_LEC | NEXT_LEC

Free C Programming Course · Chapter 5 · Lecture 4

Nested If Programs in C

Master nested if in C with the dangling else rule, the largest of three numbers and the leap year program. A hands-on lecture from our free C programming course for embedded systems.

Firmware rarely makes a single yes or no decision. A bootloader first checks that an application exists and only then checks its checksum. A motor driver first checks the enable switch and only then checks the temperature. In C these layered decisions are written as a nested if in C. This lecture is part of our free C programming course, a free C tutorial for C programming for embedded systems, and it shows how nesting works, where it goes wrong, and how to solve two classic problems with it.

What You Will Learn

  • How a nested if in C is evaluated step by step
  • Why the dangling else attaches to the wrong if and how braces fix it
  • How to find the largest of three numbers with a decision tree
  • How to write the leap year program in nested and compact form
  • When to use nested if and when to use logical operators
  • How to compile and test every example with gcc

Prerequisites

  • Lecture 3 on nested if…else and the if…else statement
  • Relational and logical operators from Chapter 4
  • gcc installed on Linux (all examples use C11)

What Is a Nested If in C?

A nested if in C is an if or if...else statement placed inside the body of another if or else. The outer condition acts as a gate. Only when it lets execution through does the program even look at the inner condition. This is how a C program expresses decisions that depend on earlier decisions: is the device powered on, and if so, is the battery healthy?

Nesting is not a new keyword or a special feature. It is simply the fact that the body of an if can be any statement, including another if. Because of that, nested if in C programs can go as deep as you like, although more than three levels is usually a sign that the logic needs to be restructured.

How a nested if decides

Outer condition: is the device powered on?

TRUE: go insideFALSE: run the outer else
▼

Inner condition: battery above 50 percent?

TRUE: healthyFALSE: low battery

Outer else branch

Device is OFF

The Dangling Else Problem

The most famous trap in nested if in C is the dangling else. The compiler does not read your indentation. It reads tokens, and it follows one fixed rule: an else always pairs with the nearest preceding if that does not already have an else. If you indent the else to line up with the outer if but forget the braces, the compiler quietly attaches it to the inner if instead.

What you meant versus what the compiler does

What the programmer meant

Indentation suggests the else lines up with the outer if.

else belongs to: if (power_on)

What the compiler built

The compiler ignores spacing and pairs the else with the closest if.

else belongs to: if (battery > 50)

Here is a small program that falls into the trap. The device is powered on and the battery is at 15 percent, so we expect to see no message at all, or at least not the message about the device being off.

#include <stdio.h>

int main(void)
{
    int power_on = 1;
    int battery = 15;

    /* Without braces: else pairs with the nearest if */
    if (power_on)
        if (battery > 50)
            printf("Battery healthy\n");
    else
        printf("Device is OFF\n");

    return 0;
}

Compile with warnings turned on and run it:

gcc -Wall -Wextra -std=c11 -o dangling dangling.c
./dangling
dangling.c: In function 'main':
dangling.c:9:8: warning: suggest explicit braces to avoid ambiguous 'else' [-Wdangling-else]
Device is OFF

The device is on, yet the program announces that it is off. The else was attached to if (battery > 50), so it ran because the battery was not above 50. Notice that gcc warned us. That is one more reason to always compile with -Wall -Wextra.

The Fix: Braces Around Every Block

#include <stdio.h>

int main(void)
{
    int power_on = 1;
    int battery = 15;

    if (power_on) {
        if (battery > 50) {
            printf("Battery healthy\n");
        }
    } else {
        printf("Device is OFF\n");
    }

    return 0;
}
(no output: power is on, but battery is not above 50, so neither message is printed)

Rule of thumb for embedded C

Write braces around the body of every if, else and loop, even when the body is one line. Coding standards such as MISRA C require this, and it prevents the dangling else and the classic bug where a second line is added later and silently falls outside the condition.

Program 1: Largest of Three Numbers Using Nested If

Finding the largest of three values is the standard exercise for nested if in C. In embedded work the same pattern picks the peak of three sensor readings or the worst of three timing measurements. The idea is a two-step tournament: compare the first two values, then compare the winner with the third.

Decision tree for the peak of three readings

Step 1: is s1 greater than or equal to s2?

TRUE: s1 is the winner so farFALSE: s2 is the winner so far
▼

Step 2a: compare s1 with s3

s1 >= s3: peak is s1otherwise: peak is s3

Step 2b: compare s2 with s3

s2 >= s3: peak is s2otherwise: peak is s3
#include <stdio.h>

int main(void)
{
    int s1, s2, s3, peak;

    printf("Enter three sensor readings: ");
    if (scanf("%d %d %d", &s1, &s2, &s3) != 3) {
        printf("Invalid input\n");
        return 1;
    }

    if (s1 >= s2) {
        if (s1 >= s3) {
            peak = s1;
        } else {
            peak = s3;
        }
    } else {
        if (s2 >= s3) {
            peak = s2;
        } else {
            peak = s3;
        }
    }

    printf("Peak reading = %d\n", peak);
    return 0;
}

Build and run it with two sets of inputs. The second set contains a tie, which the >= operators handle cleanly:

gcc -Wall -Wextra -std=c11 -o max3 max3.c
./max3
Enter three sensor readings: 7 19 12
Peak reading = 19

Enter three sensor readings: 30 2 30
Peak reading = 30

Why check the scanf return value?

scanf returns the number of items it successfully read. If the user types letters instead of numbers, the variables stay uninitialized and the program would compare garbage. Checking for a return value of 3 costs one line and removes an entire category of undefined behavior.

Program 2: Leap Year Check With Nested If

The leap year rule is a perfect fit for nesting because it has exceptions to exceptions. A year divisible by 4 is normally a leap year. But if it is also divisible by 100 it is not a leap year, unless it is divisible by 400, in which case it is a leap year after all. Real-time clock drivers and date libraries in firmware use exactly this rule.

Leap year logic as a decision tree

Is the year divisible by 100?

YES: century yearNO: ordinary year
▼

Century year: divisible by 400?

YES: leap yearNO: not a leap year

Ordinary year: divisible by 4?

YES: leap yearNO: not a leap year
#include <stdio.h>

static int is_leap_nested(int year)
{
    if (year % 100 == 0) {
        if (year % 400 == 0) {
            return 1;
        }
        return 0;
    } else {
        if (year % 4 == 0) {
            return 1;
        }
        return 0;
    }
}

static int is_leap_compact(int year)
{
    return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}

int main(void)
{
    int tests[] = { 1900, 2000, 2023, 2024, 2100, 2400 };
    int n = (int)(sizeof tests / sizeof tests[0]);

    printf("Year   Nested  Compact\n");
    for (int i = 0; i < n; i++) {
        printf("%d   %s     %s\n", tests[i],
               is_leap_nested(tests[i]) ? "yes" : "no ",
               is_leap_compact(tests[i]) ? "yes" : "no ");
    }
    return 0;
}
gcc -Wall -Wextra -std=c11 -o leap leap.c
./leap
Year   Nested  Compact
1900   no      no
2000   yes     yes
2023   no      no
2024   yes     yes
2100   no      no
2400   yes     yes

The test table includes the cases that catch most mistakes: 1900 and 2100 are century years that are not leap years, while 2000 and 2400 are century years that are. A program that only checks divisibility by 4 gets 1900 and 2100 wrong.

Nested form versus one compact condition

The function is_leap_compact expresses the whole rule in a single return statement using && and ||. Both functions give identical answers. Which one should you write?

AspectNested if…elseSingle compound condition
Readability for beginnersEach rule is on its own lineNeeds care with operator precedence
Easy to debug with a breakpointYes, step through each decisionHarder, one expression
Code sizeLongerShorter
Typical useTeaching, rules with many exceptionsSmall helper functions, macros
RiskMissing a return or braceWrong parentheses around the || part

Nested If Versus Logical Operators

Every nested if can be rewritten with && when the inner if has no else. For example, if (a) { if (b) { work(); } } is the same as if (a && b) { work(); }. Because && short-circuits, b is not even evaluated when a is false, which matters when evaluating b reads a hardware register or dereferences a pointer. Nesting becomes the better choice when the two outcomes need different else actions, as in the power and battery example above.

Common Mistakes With Nested If in C

Mistake 1: trusting indentation

The compiler never reads indentation. Always add braces, and let your editor auto-format so the layout matches what the compiler sees.

Mistake 2: a semicolon after the condition

Writing if (x > 5); makes the body an empty statement, so the following block always runs. gcc reports this with -Wempty-body.

Mistake 3: using = instead of ==

if (year = 2024) assigns 2024 and is always true. Compile with -Wall and consider writing constants on the left, as in 2024 == year.

Mistake 4: forgetting the boundary

Using > where >= was needed fails only on the exact boundary value. Always test the values on both sides of every comparison.

Best Practices

  • Keep nesting to three levels or fewer. Beyond that, split the logic into small functions with descriptive names or return early.
  • Test the boundary values of every condition, not just a typical value.
  • Use braces on every block, in line with embedded C coding standards.
  • Prefer early return or continue to flatten deep nesting in driver code.
  • Compile with -Wall -Wextra so the compiler flags ambiguous else and misleading indentation.

Performance and Safety Notes

A nested if compiles to a few compare and branch instructions, so the speed difference between nested and flat versions is negligible on a modern microcontroller. Correctness matters far more than cycles here. In safety-related firmware, an unbraced else that attaches to the wrong if can switch a motor on instead of off, which is why the habit of using braces is treated as a safety rule rather than a style choice.

Real-World Uses of Nested If in Embedded C

ScenarioOuter conditionInner condition
BootloaderIs a valid application header present?Does the checksum match?
UART driverIs the receive flag set?Is the buffer full or does it have room?
Motor controllerIs the enable switch on?Is the temperature below the limit?
Real-time clockIs the year divisible by 100?Is it divisible by 400?

Key Takeaways

  • A nested if is an if or if…else inside another if or else.
  • An else always pairs with the nearest unmatched if, no matter how the code is indented.
  • Braces around every block remove the dangling else problem.
  • The peak of three values needs a two-step comparison tree.
  • The leap year rule is a nested decision: century years need divisibility by 400, other years need divisibility by 4.
  • Check the return value of scanf and test boundary values.

Conclusion

You now know how a nested if in C works, why the dangling else bites, and how to solve two classic problems with decision trees. This lecture is part of our free C programming course, a free C tutorial built for anyone who wants to learn embedded C programming from scratch. In the next lecture we chain many conditions together with the else if ladder, which is the cleaner answer when you are choosing between several mutually exclusive cases.

Frequently Asked Questions

What is a nested if statement in C?

It is an if or if…else statement written inside the body of another if or else. The inner condition is evaluated only when the outer one allows execution to reach it.

Which if does an else belong to in C?

An else always belongs to the nearest preceding if that does not yet have an else, regardless of indentation. Use braces to make the pairing explicit.

How deep can if statements be nested in C?

The C standard requires compilers to support at least 127 levels of nesting, but readable code rarely goes beyond three levels.

Can I replace a nested if with the logical AND operator?

Yes, when the inner if has no else branch. if (a) { if (b) { … } } is equivalent to if (a && b) { … }.

How do you check for a leap year in C?

A year is a leap year if it is divisible by 400, or if it is divisible by 4 but not by 100. The nested form checks divisibility by 100 first and then by 400 or 4.

Why does gcc warn about suggest explicit braces?

The warning -Wdangling-else appears when an if without braces contains another if and an else, because the pairing may not be what the programmer intended.

Is this a good free embedded C course for beginners?

Yes. This free embedded C course explains each concept with original examples, diagrams, expected output and quizzes, and every example compiles with gcc on Linux.

Continue Your Free Embedded C Course

Next up: the else if ladder, the clean way to pick one case out of many. Keep going with this free C tutorial and build real embedded C programming skills.

PREV_LEC | NEXT_LEC

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →