Explain it simply
Explain it simply
if...else is a fork in the road inside your program. It turns decisions such as "if the password is right, show the dashboard, otherwise show an error" or "80 and above is an A, 60 and above is a B, anything else is try again" into code. When the condition is true the if block runs; when it is false the else block runs.
When there are more than two paths, you chain else if clauses. The program checks the conditions one by one from top to bottom and runs only the first block whose condition is true.
Problem → Why → Solution
The problem: when indentation lies
In an online shop, a one-line if without braces prints "In stock" only when stock is available. A month later, a teammate adds an "Added to cart" message under it with the same indentation. The code looks as if the second line is inside the if too, yet customers see Added to cart even when stock is zero.
int stock = 0;
if (stock > 0)
printf("In stock\n");
printf("Added to cart\n"); /* looks guarded, but always runs */The compiler ignores indentation
Without braces, an if controls exactly one following statement. Spaces and tabs mean nothing to a C compiler, so the second printf is simply the next statement after the if. GCC's -Wall can warn this 'if' clause does not guard..., but the real protection is to write { } on every branch, always.
Core concept: how a branch gets chosen
In if (condition) { ... } the condition can be any scalar expression, and the block runs when it is nonzero. The else block runs only when the condition is false. In an if / else if / else chain the conditions are tested top to bottom; the first true branch runs and every remaining branch is skipped entirely. That makes order matter: put score >= 60 above score >= 80 and someone with 95 gets a B, because the first test catches them.
Without braces, if and else each control a single statement. Nest unbraced ifs and you hit the dangling else: an else always pairs with the nearest if that has no else yet, whatever the indentation says. GCC warns suggest explicit braces to avoid ambiguous 'else'. Writing braces on every branch, even one-line branches, removes both of these bug classes.
Watch the boundary values. The difference between >= and > decides whether a score of exactly 80 is an A or a B. Test a range by combining conditions with &&, as in score >= 60 && score < 80, and check that neighbouring ranges leave no gap and no overlap. Rejecting invalid input (a negative score, anything over 100) first, as a guard clause at the top of the chain, means every later branch only has to think about valid data.
When all you need is to pick one of two values, the conditional operator ?: is shorter than if...else: int bonus = (attempts == 1) ? 5 : 0; reads "5 for a first-attempt pass, otherwise 0". It is an expression that yields a value, not a statement, so it fits inside assignments and printf arguments. Nested ?: chains quickly become unreadable; switch back to if...else when you are tempted.
- Test the first condition
- False: move on to the next else if
- Run only the first true branch
- Skip the rest; else if nothing matched
A chain never runs more than one branch, which is why the strictest condition belongs at the top.
General pattern
if (first_condition) {
/* runs when first_condition is true */
} else if (second_condition) {
/* runs when only second_condition is true */
} else {
/* runs when nothing above was true */
}
result = condition ? value_if_true : value_if_false;You can add as many else if clauses as you need; else is optional and can appear only once, at the end. The last line is the conditional operator, which picks one of two values.
Example: choosing a grade from a score
This program sorts a score of 72 into a grade. Before running it, substitute 72 into each condition and predict which branch it reaches. Then change the score to boundary values such as 80, 60 and 59 and run it again.
#include <stdio.h>
int main() {
int score = 72;
if (score >= 80) {
printf("Grade A");
} else if (score >= 60) {
printf("Grade B");
} else {
printf("Try again");
}
return 0;
}Code breakdown
- Line 4
int score = 72;The value under test. Change only this line to exercise every branch without touching the chain.
- Line 6
if (score >= 80) {The strictest condition is tested first. 72 >= 80 is false, so the Grade A block is skipped and the next condition is tried. A score of exactly 80 would get an A here, thanks to >=.
- Line 8
} else if (score >= 60) {Reaching this test already implies score < 80, so there is no need to write score >= 60 && score < 80. 72 >= 60 is true, so Grade B is printed.
- Lines 10-12
} else {The else block runs only if no earlier condition was true. Since the Grade B branch already ran, this block is skipped and execution jumps straight to return 0;.
Grade B- Test score >= 80 (false)
- Test score >= 60 (true)
- Print Grade B
- Skip else and leave the chain
score >= 80
Grade A
60 <= score < 80
Grade B
anything else
Try again
Guard clauses and the conditional operator
This version adds a guard at the top of the chain that rejects invalid scores. 105 is above 100, so Invalid score is printed and the grade branches are never reached; without the guard, 105 would earn a Grade A. The last lines choose a bonus with ?:, and because attempts is 2 the bonus is 0.
#include <stdio.h>
int main(void) {
int score = 105;
int attempts = 2;
if (score < 0 || score > 100) {
printf("Invalid score: %d\n", score);
} else if (score >= 80) {
printf("Grade A\n");
} else if (score >= 60) {
printf("Grade B\n");
} else {
printf("Try again\n");
}
int bonus = (attempts == 1) ? 5 : 0;
printf("Bonus points: %d\n", bonus);
return 0;
}Try the dangling else yourself
Write if (a) if (b) printf("X"); else printf("Y"); without braces, with a = 1 and b = 0, and run it. The else pairs with the inner if (b), so Y is printed. To attach it to the outer if, write if (a) { if (b) { ... } } else { ... } with braces.
In real projects
Where this shows up in real projects
The most common if in real C code is an error check: when opening a file, allocating memory or connecting to a server fails, an if catches it, reports the error and leaves the function early. That guard-clause style keeps the main logic flat instead of nested several levels deep. Validation code works the same way, rejecting bad input first and only then doing the real work.
A famous example of the danger of an unbraced if is Apple's 2014 "goto fail" bug. In code that verified SSL certificates, the line goto fail; appeared twice under an if without braces; the second copy always ran and skipped the signature check. Incidents like this are why coding standards such as MISRA C and CERT C call for braces on every if body, and why many CI pipelines build with -Wall -Werror.
Common mistakes
Common mistakes
1. A stray semicolon after if (...)
In if (score > 90); { printf("Excellent\n"); } the ; is an empty statement, and that is all the if controls. The block after it runs every time, whatever the score. GCC's -Wextra warns suggest braces around empty body in an 'if' statement.
2. Testing conditions in the wrong order
Put if (score >= 60) above if (score >= 80) and a student with 95 gets Grade B, because the first true condition ends the chain. The compiler cannot catch this, so put the strictest condition at the top.
3. Leaving a gap at a boundary
With if (score > 80) { A } else if (score < 80) { B }, a score of exactly 80 matches neither branch and falls to the else, or to nothing at all. Always test the boundary values (80, 60, 0, 100) and use >= and < consistently.
Best practices
Best practices
- Write { } on every branch, even when it holds a single line.
- Handle invalid input and error cases first, as guard clauses at the top of the chain.
- Store a complicated condition in a named variable first, such as bool isEligible = ...;.
- Run every branch and every boundary at least once before trusting the chain.
Mini challenge
Mini challenge: a shipping fee calculator
Write a program that picks a shipping fee from the package weight and ships free when the order total is $50 or more or the customer is a member. Reject an invalid weight first with a guard clause.
- If weight_kg <= 0, print an error and exit with return 1;
- Up to 1.0 kg costs $3.50, up to 5.0 kg $7.00, anything heavier $12.00 (use <= at the boundaries)
- Shipping is free when order_total >= 50.0 or is_member is true
- Every branch has braces, and the amount to pay is chosen with ?:
#include <stdio.h>
#include <stdbool.h>
int main(void) {
double weight_kg = 3.2;
double order_total = 64.0;
bool is_member = false;
double fee;
/* TODO: guard clause for weight_kg <= 0.0 (print, return 1) */
/* TODO: if / else if / else chain that sets fee by weight */
/* TODO: bool free_shipping = ... */
/* TODO: print the base fee, "Free shipping: yes/no" and the amount to pay */
return 0;
}Expected: For 3.2 kg and a $64 order: Base fee for 3.2 kg: $7.00 Free shipping: yes To pay: $0.00 Also try weight_kg = 1.0, 5.0, 5.1 and -1 to test the boundaries.
Show hint
After the guard clause, the rest of the code may assume weight_kg is greater than 0. For the amount to pay, free_shipping ? 0.0 : fee can go straight into printf.
Show solution
#include <stdio.h>
#include <stdbool.h>
int main(void) {
double weight_kg = 3.2;
double order_total = 64.0;
bool is_member = false;
double fee;
if (weight_kg <= 0.0) {
printf("Invalid weight: %.1f kg\n", weight_kg);
return 1;
}
if (weight_kg <= 1.0) {
fee = 3.50;
} else if (weight_kg <= 5.0) {
fee = 7.00;
} else {
fee = 12.00;
}
bool free_shipping = order_total >= 50.0 || is_member;
printf("Base fee for %.1f kg: $%.2f\n", weight_kg, fee);
printf("Free shipping: %s\n", free_shipping ? "yes" : "no");
printf("To pay: $%.2f\n", free_shipping ? 0.0 : fee);
return 0;
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- An if / else if / else chain tests conditions top to bottom and runs only the first true branch.
- Put the strictest condition first and test the boundary values (>= versus >) deliberately.
- Without braces an if controls one statement and an else pairs with the nearest if, so write { } on every branch.
- Reject invalid input with a guard clause first, and use ?: to pick between two values.
GNU C compiler diagnostics — GNU Project