🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →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.
Outer condition: is the device powered on?
Inner condition: battery above 50 percent?
Outer else branch
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 the programmer meant
Indentation suggests the else lines up with the outer if.
What the compiler built
The compiler ignores spacing and pairs the else with the closest if.
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
./danglingdangling.c: In function 'main':
dangling.c:9:8: warning: suggest explicit braces to avoid ambiguous 'else' [-Wdangling-else]
Device is OFFThe 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.
Step 1: is s1 greater than or equal to s2?
Step 2a: compare s1 with s3
Step 2b: compare s2 with 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
./max3Enter three sensor readings: 7 19 12
Peak reading = 19
Enter three sensor readings: 30 2 30
Peak reading = 30Why 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.
Is the year divisible by 100?
Century year: divisible by 400?
Ordinary year: divisible by 4?
#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
./leapYear Nested Compact
1900 no no
2000 yes yes
2023 no no
2024 yes yes
2100 no no
2400 yes yesThe 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?
| Aspect | Nested if…else | Single compound condition |
|---|---|---|
| Readability for beginners | Each rule is on its own line | Needs care with operator precedence |
| Easy to debug with a breakpoint | Yes, step through each decision | Harder, one expression |
| Code size | Longer | Shorter |
| Typical use | Teaching, rules with many exceptions | Small helper functions, macros |
| Risk | Missing a return or brace | Wrong 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
The compiler never reads indentation. Always add braces, and let your editor auto-format so the layout matches what the compiler sees.
Writing if (x > 5); makes the body an empty statement, so the following block always runs. gcc reports this with -Wempty-body.
if (year = 2024) assigns 2024 and is always true. Compile with -Wall and consider writing constants on the left, as in 2024 == year.
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
returnorcontinueto flatten deep nesting in driver code. - Compile with
-Wall -Wextraso 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
| Scenario | Outer condition | Inner condition |
|---|---|---|
| Bootloader | Is a valid application header present? | Does the checksum match? |
| UART driver | Is the receive flag set? | Is the buffer full or does it have room? |
| Motor controller | Is the enable switch on? | Is the temperature below the limit? |
| Real-time clock | Is 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.

2 Comments