Control Flow and Statements
This domain checks that you can trace control flow through if, switch, and the three loop forms, including fallthrough, the dangling else, and where break and continue actually transfer control.
Selection statements
- An
elsebinds to the nearest unmatchedif; braces make the intent explicit. switch (expr)requires an integer expression after promotion. Everycaselabel must be an integer constant expression, unique within the switch;defaultmay appear anywhere but only once.- Falling off the end of one
casecontinues into the next label.breakleaves the wholeswitch;continueinside aswitchthat sits inside a loop jumps to the loop's next iteration.
Iteration statements and jumps
while (cond) bodytests first;do body while (cond);tests last, always runs at least once, and needs the trailing semicolon.for (init; cond; step)allows a declaration ininit(C99), scoped to the loop;continuestill executesstepbefore re-testing.for (;;)loops forever.breakexits the innermost loop or switch;goto labeljumps within the same function only and may not jump into the scope of a variable-length array.
Worked example
int n = 0, x = 1;
switch (x) {
case 1: n += 1;
case 2: n += 2; break;
case 3: n += 4;
}
x == 1 matches case 1, adds 1, falls through into case 2, adds 2, then break exits. n is 3; case 3 never runs. With x == 3 the result would be 4, and with x == 7 it would be 0 because no label matches and there is no default.
Traps
- A missing
breakwhere fallthrough was not intended, or aswitchover an enum with nodefault. - Using a
const intvariable or a runtime value as acaselabel - only constant expressions are allowed. - A declaration cannot directly follow a
caselabel in C before C23; wrap the case body in braces. - A stray
;afterwhile (...)creates an infinite loop with an empty body. while (c = getchar())stops at the first NUL byte, not at end of file; compare againstEOFinstead.