Theory- If Else Statement in Embedded C: if, else-if Ladders, Nesting and the Dangling else-Free Embedded Course Online

🚀 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 →

MODULE 6 · LESSON 6.1 · THEORY

If Else Statement in Embedded C: if, else-if Ladders, Nesting and the Dangling else

How C decides what is true, the if, if-else and else-if forms with flow diagrams, braces, nested decisions and guard clauses, the dangling else, conditions on hardware registers, hysteresis and common mistakes. Keep this in mind whenever you use the if else statement in embedded C.

50 min
Read Time
Beginner
Level
M6 · L1
Module / Lesson

What You Will Learn

✓ What C treats as true and false, and why any non-zero value is true
✓ The if, if-else and else-if ladder, with flow diagrams
✓ Braces: why a one-line body without them is a bug waiting to happen
✓ Nested decisions and how guard clauses flatten them
✓ The dangling else problem and how the compiler pairs an else
✓ Writing conditions on registers, flags and sensor values
✓ Common mistakes: = versus ==, stray semicolons, floating-point equality
✓ Style rules used in MISRA C and professional firmware

Key Terms

ConditionTrue / falseifelseelse-if ladderNested ifDangling elseCompound statementGuard clauseShort-circuitYoda conditionBranchFlagThresholdHysteresis

1. Decisions in Embedded Programs

Firmware is mostly decisions. Is the button pressed? Has the receive buffer got a full frame? Is the temperature above the limit? Which of four states is the machine in? The if else statement in embedded C is the basic tool that turns a run of instructions into a program that reacts to its inputs. Everything else in this module, the switch statement and the loops, is built on the same idea: evaluate a condition, then choose what runs next. Many bugs in the if else statement in embedded C start here.

Unlike many languages, C has no boolean type in the core language rules for conditions. A condition is an expression of scalar type; the statement tests whether it is zero or non-zero: This is the core rule of the if else statement in embedded C.

Value of the conditionTreated asExamples
Non-zero (any bit set)true1, -7, 0.5, 0x80, a non-NULL pointer
Zerofalse0, 0.0, NULL, '\0'

Relational and logical operators (Lesson 5.1) produce exactly 1 or 0 of type int, but the if else statement in embedded C accepts any scalar value. That is why if (GPIOA->IDR & 1u) works: the AND gives 0 or 1 here, and a mask like 0x80 would give 0 or 128, both handled correctly.

truthiness.c
#include <stdio.h> #include <stddef.h> static void test(const char *label, long v) { printf(“%-22s -> %s\n”, label, v ? “true” : “false”); } int main(void) { int *p = NULL; int x = 5; test(“0”, 0); test(“1”, 1); test(“-7”, –7); test(“0x80 (a masked bit)”, 0x80); test(“x > 3”, x > 3); test(“x == 3”, x == 3); test(“p (a NULL pointer)”, p != NULL); test(“‘0’ (character zero)”, ‘0’); test(“0.0 compared to 0”, 0.0 == 0); return 0; }
Output (verified by compiling and running)
0 -> false 1 -> true -7 -> true 0x80 (a masked bit) -> true x > 3 -> true x == 3 -> false p (a NULL pointer) -> false ‘0’ (character zero) -> true 0.0 compared to 0 -> true
Watch the character: '0' is the character code 48, which is non-zero and therefore true. Only the NUL character '\0' (value 0) is false.

2. The if Statement

The simplest form runs a statement only when the condition is true. The condition is always written in parentheses, and there is no then keyword.

Syntax of if
if (condition) { statement(s); /* executed only when condition != 0 */ } next_statement; /* always executed */
Flow of a plain if statement
statements before
↓
condition ?
condition evaluated once
true (non-zero)
↓
run the body
false (zero)
↓
skip the block
↓
next statement

Notice that when the condition is false nothing special happens: execution simply continues after the body. A real example from a sensor loop:

if_basic.c
#include <stdio.h> int main(void) { int temperature = 82; /* degrees C from an ADC conversion */ int led_on = 0; printf(“temperature = %d\n”, temperature); if (temperature > 75) { led_on = 1; printf(“over-temperature warning\n”); } printf(“led_on = %d\n”, led_on); temperature = 40; if (temperature > 75) { printf(“this line is skipped\n”); } printf(“done, temperature = %d\n”, temperature); return 0; }
Output (verified by compiling and running)
temperature = 82 over-temperature warning led_on = 1 done, temperature = 40

Compound statements and braces

The body of an if is one statement. To run several, enclose them in braces { }, which turns them into a single compound statement. Technically braces are optional for a one-line body, but professional standards (MISRA C rule 15.6, CERT, the Linux kernel is the notable exception) require them, because of this classic bug:

missing_braces.c
#include <stdio.h> int main(void) { int fault = 0, shutdown = 0, alarms = 0; if (fault) alarms++; shutdown = 1; /* looks like part of the if, but is NOT */ printf(“fault=%d alarms=%d shutdown=%d\n”, fault, alarms, shutdown); return 0; }
Output (verified by compiling and running)
fault=0 alarms=0 shutdown=1
What went wrong: The indentation says shutdown = 1 belongs to the if, but only alarms++ does. With fault == 0 the machine shut down anyway. In a motor controller this kind of error is dangerous. Always use braces.

3. The if-else Statement

Add else to choose between two alternatives. Exactly one of the two bodies runs, never both and never neither.

Syntax of if-else
if (condition) { block_A; /* condition != 0 */ } else { block_B; /* condition == 0 */ }
Flow of an if-else statement
condition ?
condition evaluated once
true (non-zero)
↓
block A
false (zero)
↓
block B
↓
next statement
if_else.c
#include <stdio.h> static const char *button_text(int pressed) { if (pressed) { return “PRESSED”; } else { return “released”; } } int main(void) { for (int level = 0; level <= 1; level++) printf(“PA0 = %d -> button %s\n”, level, button_text(level)); int adc = 3072; /* 12-bit reading, full scale 4095 */ if (adc >= 2048) printf(“adc %d is in the upper half\n”, adc); else printf(“adc %d is in the lower half\n”, adc); return 0; }
Output (verified by compiling and running)
PA0 = 0 -> button released PA0 = 1 -> button PRESSED adc 3072 is in the upper half

On the STM32F407 Discovery board the user button is on PA0 and reads 1 when pressed (it is wired to 3.3 V through the button, with a pull-down). The function above would be called with (GPIOA->IDR & 1u) on the real board.

4. The else-if Ladder

When there are more than two alternatives, chain the conditions. The compiler tests them in order from top to bottom and runs the first block whose condition is true; all remaining conditions are skipped. An optional final else catches everything else.

Syntax of the else-if ladder
if (cond_1) { block_1; } else if (cond_2) { block_2; } else if (cond_3) { block_3; } else { block_default; }
A battery-level ladder: the first true test wins
level >= 80
true →
GREEN LED
false ↓
level >= 50
true →
AMBER LED
false ↓
level >= 20
true →
RED LED
false ↓
blink RED: battery critical
else_if.c
#include <stdio.h> static const char *classify(int pct) { if (pct >= 80) return “GREEN (good)”; else if (pct >= 50) return “AMBER (ok)”; else if (pct >= 20) return “RED (low)”; else return “BLINK (critical)”; } int main(void) { int samples[] = { 100, 80, 79, 50, 49, 20, 19, 0 }; for (int i = 0; i < 8; i++) printf(“battery %3d%% -> %s\n”, samples[i], classify(samples[i])); return 0; }
Output (verified by compiling and running)
battery 100% -> GREEN (good) battery 80% -> GREEN (good) battery 79% -> AMBER (ok) battery 50% -> AMBER (ok) battery 49% -> RED (low) battery 20% -> RED (low) battery 19% -> BLINK (critical) battery 0% -> BLINK (critical)

Order matters

Because the first true condition wins, a ladder must be ordered from the most specific or most restrictive test to the least. If the 20% test came first, every battery level above 20 would be reported as low. The boundary values in the table above (80, 79, 50, 49) are exactly the inputs to test: boundary value testing catches off-by-one mistakes between > and >=.

Efficiency: In a ladder the most frequent case should come first when the order is otherwise free, because later conditions are never evaluated once an earlier one succeeds.

5. Nested if Statements and Guard Clauses

An if inside another if is a nested decision. It is natural when the inner test only makes sense after the outer one succeeded, for example you may only read the received byte once the peripheral reports that data is available.

nested_if.c
#include <stdio.h> int main(void) { int usart_ready = 1; /* RXNE flag (USART2_SR bit 5) */ int framing_error = 0; /* FE flag (bit 1) */ int byte = ‘A’; if (usart_ready) { if (framing_error) { printf(“frame error, byte discarded\n”); } else { printf(“received ‘%c’\n”, byte); } } else { printf(“nothing to read\n”); } return 0; }
Output (verified by compiling and running)
received ‘A’

Deeply nested code is hard to read and test. Each extra level multiplies the paths through the function. A guard clause handles an error or special case early and returns, so the main path stays at the left margin:

guard_clause.c
#include <stdio.h> /* Nested version */ static int read_nested(int ready, int err, int byte) { int result = –1; if (ready) { if (!err) { result = byte; } } return result; } /* Flat version with guard clauses */ static int read_flat(int ready, int err, int byte) { if (!ready) return –1; if (err) return –1; return byte; } int main(void) { for (int ready = 0; ready <= 1; ready++) for (int err = 0; err <= 1; err++) printf(“ready=%d err=%d nested=%d flat=%d\n”, ready, err, read_nested(ready, err, 65), read_flat(ready, err, 65)); return 0; }
Output (verified by compiling and running)
ready=0 err=0 nested=-1 flat=-1 ready=0 err=1 nested=-1 flat=-1 ready=1 err=0 nested=65 flat=65 ready=1 err=1 nested=-1 flat=-1
Single exit versus early return: MISRA C:2004 asked for a single return per function; MISRA C:2012 relaxed this to advisory. Many teams allow early returns for guards because they reduce nesting. Follow your project rules.

6. The Dangling else

When an else could belong to more than one if, C attaches it to the nearest preceding if that does not already have an else. Indentation is ignored by the compiler, so misleading indentation hides the real structure.

dangling_else.c
#include <stdio.h> int main(void) { int a = 1, b = 0; /* The programmer wants: if (a) { if (b) X; } else Y; */ if (a) if (b) printf(“X: a and b\n”); else printf(“Y: not a\n”); printf(“— with braces —\n”); if (a) { if (b) printf(“X: a and b\n”); } else { printf(“Y: not a\n”); } return 0; }
Output (verified by compiling and running)
Y: not a — with braces —
Which if owns the else?
if (a)
↓
if (b) … else Y
else belongs to the NEAREST if
if (a) { if (b) … } else Y
braces force the intended pairing

In the first version the else pairs with if (b), not with if (a). Since a is true and b is false, it prints “Y: not a”, which is a lie: a is true. The braced version prints nothing, which is the intended result, because the outer else runs only when a is false.

Rule: Always use braces around the bodies of if and else. It removes the dangling else problem entirely. GCC’s -Wdangling-else (part of -Wparentheses/-Wall) also warns about it.

7. Writing Good Conditions for Hardware

A condition in embedded C is usually one of four things: a bit of a status register, a comparison with a threshold, a flag set by an interrupt, or a state variable.

KindTypical conditionNote
Register bitif (GPIOA->IDR & (1u << 0))The AND gives 0 or the mask; both work for truth
Several bitsif ((SR & (RXNE | ORE)) == (RXNE | ORE))Compare against the full mask for “all”
Thresholdif (adc > 2048)Decide > versus >= deliberately
Flag from an ISRif (rx_done)Flag must be volatile
Rangeif (v >= lo && v <= hi)Never write lo <= v <= hi

Range checks and the chained comparison trap

range_check.c
#include <stdio.h> int main(void) { int v = 150; int lo = 10, hi = 100; if (lo <= v <= hi) /* WRONG: (lo <= v) <= hi */ printf(“chained form says %d is in range\n”, v); if (v >= lo && v <= hi) /* correct */ printf(“correct form says %d is in range\n”, v); else printf(“correct form says %d is out of range\n”, v); return 0; }
Output (verified by compiling and running)
chained form says 150 is in range correct form says 150 is out of range

The chained form evaluates (lo <= v) to 1 and then tests 1 <= hi, which is true for any hi that is at least 1. The correct version needs &&.

Short-circuit evaluation protects dangerous tests

short_circuit_if.c
#include <stdio.h> static int calls = 0; static int expensive(void) { calls++; return 1; } int main(void) { int *p = NULL; int x = 0; if (p != NULL && *p > 0) /* *p is never evaluated when p is NULL */ printf(“positive\n”); else printf(“p is NULL or not positive (safe)\n”); if (x != 0 && expensive()) /* right side skipped */ printf(“never\n”); if (x == 0 || expensive()) /* right side skipped */ printf(“left side was enough\n”); printf(“expensive() was called %d times\n”, calls); return 0; }
Output (verified by compiling and running)
p is NULL or not positive (safe) left side was enough expensive() was called 0 times

Put the cheap or protective test on the left of && and ||. Do not depend on side effects of the right operand; they may not happen.

8. Hysteresis: A Better Threshold Decision

A single threshold makes the output flutter when a noisy signal sits near it. A thermostat that switches the fan on at 30 °C and off only at 28 °C avoids rapid switching. This needs state: the decision depends on the current output as well as the input.

hysteresis.c
#include <stdio.h> int main(void) { int temps[] = { 28, 29, 30, 31, 30, 29, 30, 29, 28, 27 }; int fan = 0; /* current output state */ printf(“temp naive hysteresis\n”); for (int i = 0; i < 10; i++) { int t = temps[i]; int naive = (t >= 30); if (!fan && t >= 30) fan = 1; /* switch on at 30 */ else if (fan && t <= 28) fan = 0; /* switch off at 28 */ printf(“%4d %5d %10d\n”, t, naive, fan); } return 0; }
Output (verified by compiling and running)
temp naive hysteresis 28 0 0 29 0 0 30 1 1 31 1 1 30 1 1 29 0 1 30 1 1 29 0 1 28 0 0 27 0 0

The naive column toggles four times, while the hysteresis column changes only twice. This pattern (a Schmitt trigger in software) is used for thermostats, battery cut-offs and light sensors.

9. Branches, Code Size and Speed on the Cortex-M4

An if compiles to a compare followed by a conditional branch. On the Cortex-M4 a taken branch costs about 2 to 4 cycles because the pipeline refills, while a not-taken branch costs 1 cycle. For very short bodies the compiler can use an IT (if-then) block, which executes one to four conditional instructions without branching. You almost never need to optimise this by hand; write clear code and measure first.

TechniqueEffectWhen
Put the common case firstFewer conditions evaluated on averageLadders on hot paths
Replace long ladders on one variableA switch may become a jump table (Lesson 6.2)Many discrete values
__builtin_expect(cond, 1)Tells GCC which way is likely, so it lays out the code accordinglyRare error paths
Avoid branches with boolean arithmeticcount += (x > 0);Only when profiling shows a gain
Warning on micro-optimisation: Readable code first. Compilers at -O2 already convert simple ternaries and short ifs to IT blocks or conditional moves.

10. Common Mistakes

Mistake 1 — = instead of ==: if (x = 5) assigns and is always true. Enable -Wall; consider writing if (5 == x) so a typo does not compile.
Mistake 2 — stray semicolon after the condition: if (x > 3); makes the body an empty statement, and the following block always runs.
Mistake 3 — missing braces: Adding a second statement under an unbraced if does not put it inside.
Mistake 4 — comparing floating-point numbers with ==: 0.1 + 0.2 == 0.3 is false. Compare with a tolerance: fabsf(a - b) < eps.
Mistake 5 — unreachable else-if branches: A ladder ordered from general to specific makes the later tests dead code.
Mistake 6 — testing a flag that is not volatile: The compiler may read the flag once and never see the ISR update.
Mistake 7 — relying on side effects in the right operand of && or ||: The right side may be skipped.
Mistake 8 — chained comparisons: a < b < c does not mean what mathematics says.

Stray Semicolon and Assignment: Real GCC Output

Both of the following compile, but GCC with -Wall -Wextra points to the likely bugs. This is the single most useful habit for the if else statement in embedded C: read every warning.

bugs.c
#include <stdio.h> int main(void) { int x = 4; if (x = 5) printf(“assigned\n”); if (x > 3); printf(“always runs\n”); return 0; }
Warnings for two classic if bugs
bugs.c: In function ‘main’: bugs.c:5:9: warning: suggest parentheses around assignment used as truth value [-Wparentheses] 5 | if (x = 5) | ^ bugs.c:7:15: warning: suggest braces around empty body in an ‘if’ statement [-Wempty-body] 7 | if (x > 3); | ^ bugs.c:7:5: warning: this ‘if’ clause does not guard… [-Wmisleading-indentation] 7 | if (x > 3); | ^~ bugs.c:8:9: note: …this statement, but the latter is misleadingly indented as if it were guarded by the ‘if’ 8 | printf(“always runs\n”); | ^~~~~~

11. Best Practices for the if else statement in Embedded C

  • Always use braces, even for one-line bodies.
  • End every else-if ladder with a final else that handles or reports the impossible case (MISRA rule 15.7).
  • Keep conditions simple; give complex ones a name: bool overheated = (t > MAX_T);.
  • Prefer positive conditions and guard clauses to deep nesting (three levels is a practical limit).
  • Name thresholds with #define or const; do not scatter magic numbers.
  • Test boundary values: just below, equal and just above each threshold.
  • Use hysteresis for noisy analog inputs.
  • Declare ISR-shared flags volatile and clear them deliberately.

Key Takeaways — Lesson 6.1

  • The if else statement in embedded C tests a condition for non-zero (true) or zero (false).
  • if runs a body conditionally; if-else chooses exactly one of two; an else-if ladder picks the first true condition.
  • Always brace the bodies; the dangling else pairs with the nearest unmatched if.
  • Flatten nested decisions with guard clauses.
  • lo <= v <= hi is wrong; write v >= lo && v <= hi.
  • Short-circuit evaluation lets a left-hand test protect the right-hand one.
  • Use hysteresis for noisy thresholds and test boundary values.

Frequently Asked Questions

What is true and false in C?
Zero is false and every non-zero value is true. Relational and logical operators produce 1 or 0 as an int, but an if statement accepts any scalar, including pointers and floating-point values.
Do I need braces for a one-line if body?
Syntactically no, but professional standards (MISRA C, CERT C) require them. Without braces a second statement added later silently falls outside the if.
What is the dangling else problem?
When an else could pair with more than one if, C pairs it with the nearest preceding if that has no else. Braces make the intended pairing explicit.
What is the difference between else-if and several separate ifs?
In an else-if ladder at most one block runs and later conditions are not evaluated once one is true. Separate if statements are all evaluated independently and several bodies may run.
How do I check that a value is within a range?
Use two comparisons joined by &&: v >= lo && v <= hi. The expression lo <= v <= hi compiles but gives wrong answers.
Is an if statement slow on a Cortex-M4?
A taken branch costs a few cycles because of the pipeline refill, a not-taken branch one cycle. For short bodies GCC often uses IT blocks. Clarity matters more than micro-optimisation.

Ready to practise?

Next: worked examples with button handling, battery levels, range checks, state decisions and hysteresis on real output.

💬 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 →