if, else, and else if
beginner11 min readLesson 15 of 148
The decision ladder: exact syntax, common shapes, and the dangling-else pitfall.
The ladder
if (score >= 90) {
grade = 'A';
} else if (score >= 80) {
grade = 'B';
} else {
grade = 'F';
}
Conditions test top to bottom; the FIRST true branch runs and the rest are
skipped. The final else catches everything remaining โ put the most specific
test first.
Brace discipline
Braces are optional for a single statement โ and a standing trap:
if (x > 0)
printf("positive\n");
printf("always prints!\n"); // NOT part of the if
Rule for this course: always brace.
Ternary: a tiny if as an expression
const char* sign = (x >= 0) ? "non-negative" : "negative";
Use it for choosing a value; keep real logic in if.