🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Debugging C if Statements
Four classic if-else traps explained – a free C tutorial for safer embedded C programming
Why Debugging C if Statements Is a Core Skill
Debugging C if statements is where many students lose marks and many firmware engineers lose weekends. A single = typed instead of ==, or a stray semicolon, silently changes program behaviour and the compiler often stays quiet. In this lecture of our free C programming course you will read short, tricky programs, predict their output, and then verify the answer by running them. These are the same traps that appear in written tests, interviews and real embedded C programming code reviews.
What You Will Learn
- Why assignment inside a condition always changes behaviour
- What a semicolon after
if (...)really does - How the dangling else attaches to the nearest if
- How
&&,||and!precedence changes results - A step-by-step method to predict output without running the code
Prerequisites
- The
if,if-elseand nested if statements - Relational and logical operators from the Operators chapter
- Truth in C: zero is false, any non-zero value is true
A Method to Predict Output
Step 3 is the one people skip. Indentation is for humans; the compiler ignores it. Only braces and semicolons decide which statements belong to an if.
Trap 1: Assignment Inside a Condition
int mode = 3;
if (mode = 7)
printf("branch A, mode=%d\n", mode);
else
printf("branch B, mode=%d\n", mode);
The expression mode = 7 assigns 7 to mode and its value is 7. Seven is non-zero, so the condition is true and the first branch runs. The variable also got overwritten, which is the second damage. The fix is mode == 7.
if (status = read_status()) may be intentional, but when you meant a comparison with a constant it silently overwrites your state variable. Write constants on the left, such as if (7 == mode), so a typo becomes a compile error.
Trap 2: Semicolon After if
int temp = 90;
if (temp > 100);
printf("overheat check done\n");
The lone semicolon is an empty statement, which becomes the entire body of the if. The printf is a separate statement that runs every time, even when temp is 90. Compile with -Wall and GCC warns about the empty body or suspicious indentation.
Trap 3: Dangling else
int x = 1, y = 5;
if (x == 1)
if (y == 9)
printf("both match\n");
else
printf("else attached to inner if\n");
The visual indentation suggests the else pairs with x == 1. The C rule is different: an else belongs to the nearest unmatched if. Here that is y == 9, so the else runs because x is 1 but y is not 9. Use braces to remove all doubt:
if (x == 1) {
if (y == 9) {
printf("both match\n");
}
} else {
printf("x is not 1\n");
}
Trap 4: Logical Operator Precedence
int a = 0, b = 1, c = 0;
if (a || b && c)
printf("T\n");
else
printf("F\n");
if (!a && b || c)
printf("T2\n");
int q = 3;
if (!q == 0)
printf("not-q equals zero\n");
else
printf("else path\n");
| Expression | Evaluation order | Result |
|---|---|---|
a || b && c | b && c first (AND binds tighter), then OR | 0 || 0 = 0 (false) |
!a && b || c | !a, then AND with b, then OR with c | 1 (true) |
!q == 0 | !q first = 0, then 0 == 0 | 1 (true) |
The last one surprises beginners: !q == 0 is not “q is not equal to zero”. Logical NOT binds tighter than ==, so it is read as (!q) == 0.
Build, Run and Check Your Predictions
Put all four traps into one file named ep_if_traps.c, compile, and compare with your hand predictions.
$ gcc -Wall -std=c11 -o ep_if_traps ep_if_traps.c
$ ./ep_if_traps
branch A, mode=7
overheat check done
else attached to inner if
F
T2
not-q equals zero
GCC with -Wall also prints warnings for the assignment used as a truth value, the empty if body and the ambiguous else. Treat every such warning as a bug report, not noise.
Worked Example: A Firmware Mode Check
Imagine a small controller that switches a heater according to a mode variable. A tired developer writes the check below and the heater turns on in every mode:
#define MODE_HEAT 2
void update_heater(int mode, int temp)
{
if (mode = MODE_HEAT);
if (temp < 40)
heater_on();
else
heater_off();
}
Three of our traps hide in six lines. First, mode = MODE_HEAT overwrites the argument with 2, so the condition is always true. Second, the semicolon makes the first if do nothing. Third, the else now pairs with temp < 40, not with the mode check. A corrected, defensive version looks like this:
void update_heater(int mode, int temp)
{
if (MODE_HEAT == mode) {
if (temp < 40) {
heater_on();
} else {
heater_off();
}
} else {
heater_off();
}
}
Notice the constant on the left, the braces everywhere and the explicit else for the non-heating mode. Code review checklists in embedded teams are full of exactly these rules because a wrong branch can mean hardware damage, not just a wrong printout.
Common Mistakes Summary
| Mistake | Effect | Defence |
|---|---|---|
= instead of == | Always true for non-zero; variable overwritten | Constant on the left, -Wall |
| Semicolon after if | Next statement always runs | Always use braces |
| Missing braces | Dangling else pairs with wrong if | Brace every branch |
| Mixed && and || without parentheses | Unexpected grouping | Add parentheses for clarity |
Best Practices for Embedded C Programming
- Brace every if, else and loop body, even for one-liners; MISRA C guidelines require it.
- Compile with
-Wall -Wextraand fix warnings before testing on hardware. - Parenthesise mixed logical expressions so intent is visible to reviewers.
- Keep conditions simple; assign to a descriptive boolean first, then test it.
Self-check
Before running, predict the output of the trap programs on paper. If your prediction matches, you have understood how C really reads conditions.
Summary and Key Takeaways
- Assignment in a condition gives the assigned value as the truth value.
- A semicolon after
if (...)makes the if do nothing. - An else always binds to the nearest unmatched if.
- Logical NOT binds tighter than comparison; AND binds tighter than OR.
Mastering how to spot these problems makes debugging C if statements faster and your embedded C programming safer. The next lecture trains the same prediction skill on loops.
Frequently Asked Questions
Why does if (a = 5) always run the true branch?
The assignment expression returns 5, which is non-zero, so the condition is true.
What happens with a semicolon after an if condition?
The semicolon is an empty statement that becomes the body. The following statement is no longer controlled by the if.
Which if does an else belong to in C?
The nearest preceding if that does not already have an else.
Is !x == 0 the same as x != 0?
No. It is parsed as (!x) == 0, which is true when x is non-zero.
Does this free embedded C course cover debugging habits?
Yes, each lecture includes mistakes, best practices, quizzes and interview questions.
Keep Going in the Free C Tutorial
Next up: trace loops, goto, while and do-while by hand and learn to spot infinite loops before they hang your firmware.

2 Comments