$ overview
overview/0x04·Control Flow

Conditionals

Branching with if, else, and switch — and how truth works in C.

Branching lets a program take different paths depending on a condition. In C, any nonzero value counts as "true" and 0 counts as "false" — there's no separate boolean type to reason about, just numbers.

if, else if, else

grade.c
1#include <stdio.h>
2 
3int main(void) {
4 int score = 82;
5 
6 if (score >= 90) {
7 printf("A\n");
8 } else if (score >= 80) {
9 printf("B\n");
10 } else if (score >= 70) {
11 printf("C\n");
12 } else {
13 printf("F\n");
14 }
15 return 0;
16}

Conditions are checked top to bottom, and the first true branch runs — the rest are skipped, even if they'd also be true.

warning: Braces are optional for single statements — use them anyway
Indentation doesn't create a block in C. The second printf above always runs, because only the first statement belongs to the if. Wrapping the body in { } avoids this trap entirely.
dangling-else.c
1if (score >= 90)
2 printf("A\n");
3 printf("Great job!\n"); // runs unconditionally, despite the indentation

switch

A switch compares one value against several constant cases — clearer than a long if/else if chain when you're testing a single variable for equality:

switch.c
1int day = 3;
2 
3switch (day) {
4 case 1:
5 printf("Monday\n");
6 break;
7 case 2:
8 printf("Tuesday\n");
9 break;
10 case 3:
11 printf("Wednesday\n");
12 break;
13 default:
14 printf("Some other day\n");
15}
error: Forgetting break falls through
Without break, execution continues into the next case regardless of whether it matches. This is sometimes intentional (grouping cases with shared behavior), but it's the source of many switch-statement bugs. Always add break unless fall-through is exactly what you want — and comment it when it is.

The ternary operator

For a simple choice between two values, the ternary operator ?: is a compact alternative to a full if/else:

ternary.c
1int max = (a > b) ? a : b;
2// equivalent to:
3// int max; if (a > b) { max = a; } else { max = b; }