🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →C if else Statement
Master the if else statement in C: syntax, flow, truth values and real examples. A practical lecture from our free C programming course for embedded systems.
The if else statement in C is the first tool every programmer reaches for when code must make a decision. A battery monitor checks if the voltage is low, a motor driver checks if the limit switch is pressed, and a parser checks if a packet is valid. In this lecture of our free C programming course you will learn exactly how if and if...else work, how C decides what is true or false, and how to avoid the classic mistakes. This free C tutorial is written for students learning embedded C programming, so examples lean towards sensors, thresholds and registers.
What You Will Learn
- The two syntax forms of the if statement and the if else statement in C
- How C treats zero and nonzero values as false and true
- How to read a flow chart of if and if…else
- Four complete programs with build commands and expected output
- The assignment-instead-of-comparison bug and the stray semicolon bug
- Best practices for embedded C programming decisions
Prerequisites
- Lecture 1 of this chapter: control statements and compound statements (blocks)
- Relational operators (
<,>,==,!=) and the remainder operator% - Basic use of
printfandscanf
How C Decides True and False
The if statement is a bi-directional conditional control statement: it tests a condition and takes one of two possible actions. Before looking at the syntax, you need one rule that surprises many beginners. C has no separate boolean type in its original design, so the condition is an ordinary number.
| Value of the condition | Treated as | Example |
|---|---|---|
| Zero | False | 0, 5 - 5, 3 > 9 |
| Any nonzero value | True | 1, -6, 42, 9 > 3 |
A relational expression such as temp < 0 produces exactly 1 when it holds and 0 when it does not. That is why you can also write if (count) to mean “if count is not zero” and if (!flag) to mean “if flag is zero”.
The if Statement Syntax
The simplest form runs a statement only when the condition is true. If the condition is false, the statement is skipped and execution continues with the next statement after the if. The part after the condition can be a single statement or a block.
/* Form 1: single statement */
if (condition)
statement1;
/* Form 2: block of statements */
if (condition)
{
statement_a;
statement_b;
}
Example 1: if Statement with scanf
This program warns when the temperature is below freezing. Notice that the second printf is not part of the if, so it always runs.
/* cp5_2_freeze.c : simple if statement */
#include <stdio.h>
int main(void)
{
int temp;
printf("Enter temperature in C: ");
scanf("%d", &temp);
if (temp < 0)
printf("Below freezing\n");
printf("Reading stored: %d\n", temp);
return 0;
}
$ gcc -Wall -Wextra -std=c11 cp5_2_freeze.c -o cp5_2_freeze
$ ./cp5_2_freeze
Enter temperature in C: -6
Below freezing
Reading stored: -6
$ ./cp5_2_freeze
Enter temperature in C: 25
Reading stored: 25
The if else Statement in C
When you need two paths, add an else. If the condition is true, statement1 runs. Otherwise statement2 runs. In both cases, control then moves to the statement that follows the whole if...else. Exactly one of the two branches executes, never both and never neither.
/* Form 1: single statements */
if (condition)
statement1;
else
statement2;
/* Form 2: blocks */
if (condition)
{
statement_a;
}
else
{
statement_b;
}
Example 2: Maximum and Minimum of Two Readings
Firmware often compares two sensor samples. This program prints which is larger and which is smaller using an if…else.
/* cp5_2_minmax.c : if...else with two branches */
#include <stdio.h>
int main(void)
{
int a, b;
printf("Enter two readings: ");
scanf("%d %d", &a, &b);
if (a > b)
printf("max = %d, min = %d\n", a, b);
else
printf("max = %d, min = %d\n", b, a);
return 0;
}
$ ./cp5_2_minmax
Enter two readings: 42 17
max = 42, min = 17
$ ./cp5_2_minmax
Enter two readings: 9 9
max = 9, min = 9
When both readings are equal the condition a > b is false, so the else branch runs. The answer is still correct, which shows why it is worth thinking about the boundary case each time you write a condition.
Example 3: Even or Odd Packet Number
The remainder operator gives an easy parity test. If a number divided by 2 leaves remainder 0, it is even. This idea is used in real code, for example to pick alternating buffers (ping-pong buffering).
/* cp5_2_parity.c : even or odd check */
#include <stdio.h>
int main(void)
{
int packet;
printf("Enter packet number: ");
scanf("%d", &packet);
if (packet % 2 == 0)
printf("Packet %d is even: use buffer A\n", packet);
else
printf("Packet %d is odd: use buffer B\n", packet);
return 0;
}
$ ./cp5_2_parity
Enter packet number: 15
Packet 15 is odd: use buffer B
$ ./cp5_2_parity
Enter packet number: 8
Packet 8 is even: use buffer A
Example 4: Blocks in Both Branches
When a branch needs more than one statement, use braces (see Lecture 1). Here a battery monitor takes two actions in each branch.
/* cp5_2_battery.c : blocks in if and else */
#include <stdio.h>
int main(void)
{
int percent = 12;
if (percent < 20)
{
printf("Battery low\n");
printf("Reducing display brightness\n");
}
else
{
printf("Battery healthy\n");
printf("Normal brightness\n");
}
return 0;
}
$ ./cp5_2_battery
Battery low
Reducing display brightness
Common if else Mistakes in C
Mistake 1: Using = Instead of ==
This is the number one bug in embedded C programming. A single equals sign assigns a value, and the assigned value then becomes the condition.
/* cp5_2_assign_bug.c */
#include <stdio.h>
int main(void)
{
int ready = 0;
if (ready = 1) /* BUG: assignment */
printf("Always runs\n");
return 0;
}
$ gcc -Wall -Wextra -std=c11 cp5_2_assign_bug.c -o cp5_2_assign_bug
cp5_2_assign_bug.c: In function 'main':
cp5_2_assign_bug.c:8:9: warning: suggest parentheses around assignment used as truth value [-Wparentheses]
$ ./cp5_2_assign_bug
Always runs
The variable ready started as 0, but the condition set it to 1 and then tested 1, which is true. The fix is if (ready == 1) or simply if (ready). Some teams write constants on the left, as in if (1 == ready), so that a typo like 1 = ready becomes a compile error.
Mistake 2: A Stray Semicolon After the Condition
if (temp > 80); /* BUG: empty statement */
printf("Overheat\n"); /* always runs */
The semicolon is an empty statement, so the if controls nothing. The printf runs every time.
Mistake 3: Missing Braces
Without braces only the first statement belongs to the branch. Always use braces, as covered in Lecture 1.
| Mistake | Symptom | Fix |
|---|---|---|
= instead of == | Condition always true or false, variable changes | Use ==, enable -Wall |
Semicolon after if (...) | Statement runs unconditionally | Remove the semicolon |
| No braces around several statements | Only one statement is conditional | Always use braces |
Comparing floats with == | Unexpected false results | Compare against a small tolerance |
| Forgetting the boundary value | Off-by-one behaviour at the limit | Decide between < and <= on purpose |
Best Practices for if else in Embedded C Programming
- Write braces every time, even for one line.
- Test the positive condition first so the code reads naturally:
if (sensor_ok) { ... } else { ... }. - Name your flags:
if (rx_complete)reads better thanif (f1). - Replace magic numbers with named constants, for example
#define TEMP_LIMIT 80. - Check both sides of every limit when testing: just below, equal, just above.
- Keep conditions short. Move a long condition into a small helper function with a clear name.
Performance and safety note
A single if compiles to a compare and a conditional jump, which is extremely cheap, even on a small microcontroller. In interrupt service routines, keep the decision logic short, set a flag, and finish the heavy work in the main loop. Inputs from outside the system (UART bytes, sensor values) should always be range-checked with an if before they are used as an array index.
Summary and Key Takeaways
ifruns a statement or block only when the condition is nonzero (true).if...elsechooses exactly one of two paths, then continues with the next statement.- Zero is false and every other value is true.
- Use
==to compare, never=. - Never place a semicolon straight after the closing parenthesis of the condition.
- Braces turn several statements into one controlled unit.
You now understand single-level decisions. Real firmware often needs a decision inside another decision, and that is exactly what the next lecture of this free embedded C course covers: nesting of if…else and the famous dangling else.
Quick Quiz
Q1. What is printed by if (0) printf("A"); else printf("B");?
B, because zero is false.
Q2. What does if (-3) do?
The condition is true because -3 is nonzero.
Q3. In Example 2, why is the else branch used when both numbers are equal?
The condition a > b is false for equal numbers, so the else branch runs.
Q4. Why does if (x = 5) always succeed?
It assigns 5 to x, and the value of the assignment (5) is nonzero.
Interview Questions
1. How does C represent true and false?
Zero is false. Any nonzero value is true. Relational and logical operators yield 1 or 0.
2. What is the difference between if and if…else?
An if alone skips the statement when false. With else, one of two alternative paths always runs.
3. What does a semicolon right after if (condition) do?
It forms an empty statement, so the if has no effect and the following statement always executes.
4. Why is if (x = 0) dangerous?
It assigns 0 to x and the condition is always false. It is almost always a typo for ==.
5. How would you check if a number is even?
if (n % 2 == 0), or with bitwise AND: if ((n & 1) == 0).
Frequently Asked Questions
What is the syntax of the if else statement in C?
if (condition) statement1; else statement2;, where each statement can also be a block in braces.
Can I use else without if in C?
No. An else must always follow an if and belongs to it.
Is the else part mandatory?
No. A plain if is valid and is used when nothing needs to happen for the false case.
Does C have a boolean type?
Since C99 you can include stdbool.h to use bool, true and false, but conditions still treat any nonzero value as true.
Is this a free embedded C course?
Yes. This free C programming course from EmbeddedPathashala is aimed at students who want to learn C programming for embedded systems.
Can the condition contain multiple tests?
Yes, you can combine tests with the logical operators &&, || and !, which were covered in the operators chapter.
Suggested Images
- Decision diamond for if. ALT: “if else statement in C flow chart for a free C programming course”
- Terminal screenshot of the assignment bug warning. ALT: “if else statement in C assignment bug warning in embedded C programming”
- True and false table for C conditions. ALT: “C true and false values in a free C tutorial for embedded systems”
Keep Going With Our Free C Tutorial
Next lecture: nested if…else and the dangling else problem. Continue the free embedded C course at your own pace.

2 Comments