CC Explainer
C · 1 · Foundations3 / 35 · 9%

Control Flow & Functions

if / for / while / switch and the function contract that binds them.

Examples: if, for, while, switch, return

shortcuts: ← prev · → next · M mark
1

if / else

The staple branching form. Each branch is a statement or a { } block.

Example
example
int score = 82;
if (score >= 90)      puts("A");
else if (score >= 80) puts("B");
else                  puts("C or lower");
2

for & while Loops

Two shapes for the same idea: init → test → step.

Example
example
for (int i = 0; i < 5; i++) printf("%d ", i);

int j = 0;
while (j < 5) { printf("%d ", j); j++; }

do { j--; } while (j > 0);
Output
0 1 2 3 4 0 1 2 3 4
3

switch

Fast dispatch on integer/char/enum values. Don't forget break!

Example
example
switch (op) {
    case '+': r = a + b; break;
    case '-': r = a - b; break;
    default:  puts("unknown"); break;
}
WATCH OUT
Missing break falls through to the next case — sometimes intended, usually a bug.
4

Functions

Named, typed, reusable units. Prototype in .h, body in .c.

Example
example
// area.h
int area(int w, int h);

// area.c
int area(int w, int h) {
    return w * h;
}

// main.c
#include "area.h"
int main(void) { return area(3, 4); }