Conditionals
Conditionals choose which statement runs based on a value. C offers if/else if/else for arbitrary tests and switch for dispatching on a single integer value.
Detailed Explanation
An if takes a scalar expression and runs its body when that expression compares unequal to zero. That is the whole rule, and it explains most of C's conditional quirks.
C had no boolean type until C99. Any arithmetic or pointer value works as a condition: zero, the null pointer, and '\0' are false, everything else is true. This is why if (n) means "n is not zero", if (p) means "p is not null", and while (*s) walks a string to its terminator. C99 added _Bool, plus the macros bool, true, and false in <stdbool.h>; C23 promotes bool, true, and false to keywords. Assigning to a _Bool normalises any non-zero value to exactly 1, which is the one place C does the conversion for you.
The chain form is if/else if/else. There is no elif keyword: else if is an else whose body happens to be another if. The chain stops at the first true test, so ordering matters when the conditions overlap.
switch is the other form. It evaluates one integer expression, then jumps to the case label whose constant matches, or to default if none does. The constants must be integer constant expressions known at compile time, so you cannot switch on a string or on a runtime range. There is no ordering requirement on the labels, and default may appear anywhere, though putting it last is conventional.
The feature that trips everyone is fallthrough. A case is a label, not a block. Once control lands on a label it keeps running straight through subsequent labels until it hits a break, a return, or the end of the switch. Forgetting a break is a classic bug, so modern compilers offer -Wimplicit-fallthrough and you mark the deliberate cases with a comment like /* fall through */ or the C23 [[fallthrough]] attribute.
Deliberate fallthrough is genuinely useful when several labels share one body, which is the case in most parsers and state machines.
Two more rules worth knowing.
The dangling else. An else binds to the nearest unmatched if, regardless of how the source is indented. Written without braces, if (a) if (b) x(); else y(); attaches the else to if (b), not to if (a). Indentation lies here, braces do not.
Always brace. Even a one-line body. The cost is two characters; the benefit is that adding a second statement later cannot silently move it outside the conditional. The goto fail bug in Apple's TLS implementation was exactly this shape.
Switching on an enum is where switch earns its place over an if chain. If you list every enumerator and omit default, -Wswitch (included in -Wall) warns whenever someone adds a new enumerator and forgets to handle it here. That turns a runtime surprise into a compile-time nudge. Adding default: break; silences the warning permanently, so leave it out when exhaustiveness is what you want, and use it only when the value can genuinely arrive from outside your program.
Code Examples
#include <stdbool.h> // C99: bool, true, false
#include <stdio.h>
static const char *grade_for(int score) {
// The chain stops at the first true test, so the order encodes the ranges.
if (score >= 90) {
return "A";
} else if (score >= 80) {
return "B";
} else if (score >= 70) {
return "C";
} else {
return "F";
}
}
int main(void) {
printf("%s\n", grade_for(85)); // B
// Any scalar works as a condition. These three tests are all idiomatic.
int count = 0;
const char *name = NULL;
if (!count) { printf("count is zero\n"); }
if (!name) { printf("name is null\n"); }
// A _Bool normalises anything non-zero to 1.
bool flag = 42;
printf("flag = %d\n", flag); // 1
// Dangling else: the else belongs to the INNER if, despite the layout.
int a = 0, b = 1;
if (a)
if (b) printf("both\n");
else printf("this runs when a is true and b is false\n");
// Nothing prints here, because a is 0. Braces would have made that obvious.
return 0;
}#include <stdio.h>
enum token_kind {
TOKEN_NUMBER,
TOKEN_PLUS,
TOKEN_MINUS,
TOKEN_EOF
};
static const char *describe(enum token_kind kind) {
switch (kind) {
case TOKEN_PLUS:
case TOKEN_MINUS:
// Deliberate shared body: both labels fall into the same statements.
return "operator";
case TOKEN_NUMBER:
return "number";
case TOKEN_EOF:
return "end of input";
}
// No default: with -Wall, adding TOKEN_STAR to the enum makes the
// compiler warn that this switch no longer covers every enumerator.
return "unknown";
}
static int count_vowels(const char *s) {
int vowels = 0;
for (const char *p = s; *p != '\0'; p++) {
switch (*p) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
vowels++;
break; // without this, control would run into the default
default:
break;
}
}
return vowels;
}
int main(void) {
printf("%s %s\n", describe(TOKEN_PLUS), describe(TOKEN_EOF));
printf("%d\n", count_vowels("sequence point")); // 6
return 0;
}Common Gotchas
`=` compiles where you meant `==`
`if (status = OK)` assigns and then tests the assigned value, so the branch always runs when `OK` is non-zero. Enable `-Wparentheses` (part of `-Wall`), and wrap deliberate assignments in an extra pair of parentheses so the warning stays meaningful.
A declaration cannot follow a `case` label directly
in C99 and C11 a label must be followed by a statement, and a declaration is not a statement, so `case 1: int x = 0;` is a constraint violation. Wrap the body in braces: `case 1: { int x = 0; ... break; }`. Jumping over an initialization inside a switch also leaves the variable uninitialized.
Missing `break` falls through silently
the compiler assumes you meant it unless you enable `-Wimplicit-fallthrough`. Turn that warning on and annotate the intentional cases.
Floating-point comparisons are not the exception you expect
`if (x == 0.1 + 0.2)` fails for `double` because the values are not exactly representable, and any NaN compares false against everything, including itself. Compare against a tolerance, or use `isnan` from `<math.h>`.