Conditions, choices, and loops
Follow how execution selects a path, repeats work, and transfers control, with careful attention to boundaries and progress.
In this chapter10 sections
A program often needs to choose what happens next or repeat some work. Conditions and loops express those choices. We will follow small examples step by step so the first test, repeated work, and stopping point stay visible.
1. A condition is a test of the current state
An if tests a scalar condition when execution reaches it. If the result is nonzero, its controlled statement runs. Zero is false; negative integers are true. The test happens at that point in execution, rather than continuously watching for changes.
int age = 17;
int eligible;
if (age >= 18) {
eligible = 1;
} else {
eligible = 0;
}Exactly one of these two branches supplies the value. The example gives eligible a value on every path before using it afterward. An else is optional in C, but if you leave it out, you must still reason about what happens on the false path. The grammar attaches an else to the nearest eligible unmatched if; braces make your intended structure clearer.
2. While tests before the body
int count = 0;
while (count < 3) {
count += 1;
}The while test happens before each possible repetition. Here the body runs with counts zero, one, and two. After the third update, the count is three and the next test is false. If the very first test were false, the body would run zero times.
For a loop intended to finish, identify what makes progress toward a false condition or another exit. Forgetting an update can make the behavior differ radically from the specification. For a loop intended to keep serving events, identify the event and resource rules instead. Do not justify a loop merely by saying “it seems to stop on my machine.”
3. For places related loop controls together
int sum = 0;
for (int value = 1; value <= 3; ++value) {
sum += value;
}Read the for in order: initialise, test, run the body, update, then test again. Here the body adds one, two, and three, giving six. The loop variable declared in this header is visible within the loop. It is not available to unrelated code after the loop.
The two semicolons inside the parentheses separate the control parts. A semicolon immediately after the closing parenthesis is different: it can be a null statement that becomes the whole loop body. A later brace block is then not automatically repeated. This can be valid syntax with an unintended meaning, so indentation alone does not protect you.
4. Do-while checks after an initial execution
int count = 3;
do {
count += 1;
} while (count < 3);When control enters this do statement normally, the body runs before the first test. The count becomes four, then the condition is false. This form is useful when there is meaningful work to perform before deciding whether to repeat. Its trailing semicolon belongs to the syntax and is not the accidental empty loop body discussed above.
5. Break and continue have different destinations
break leaves the nearest enclosing loop or switch. continue moves to the loop’s continuation step. For a for, that includes the update before the next test. For while and do-while, it leads to the test. Neither word automatically leaves every surrounding construct.
int sum = 0;
for (int value = 1; value <= 3; ++value) {
if (value == 2) {
continue;
}
sum += value;
}The second iteration skips the addition, but it does not skip the for update. One and three are added, giving four. In nested control flow, first identify the actual enclosing construct. A break inside a switch nested in a loop breaks that switch, not the outer loop.
return leaves the current function, optionally supplying the result required by its return type. goto transfers control to a label in the same function, subject to scope restrictions; it is not a jump into another function. A shared resource-cleanup path is one useful pattern, while ordinary choices and repetitions are usually clearer with structured statements.
6. Switch selects a label, not an isolated box
int choice = 2;
int charge = 0;
switch (choice) {
case 1:
charge = 10;
break;
case 2:
charge = 20;
break;
default:
charge = -1;
break;
}switch selects a label using an integer value. A case supplies a permitted constant value; default supplies a fallback. Execution can continue past the selected case into later code. Use break or another deliberate transfer when that continuation is not intended. The integer promotion and constant-expression rules still apply.
7. State the boundary and what remains true
An invariant is a fact kept true at chosen points in a computation. In the sum loop, just before processing value k, the sum contains the earlier values already added. Check that this is true at the start and remains true after an iteration. A comment stating it is not proof by itself.
Check the first and last iteration, zero iterations, and whether arithmetic can cross a type’s range. Replacing < with <= may add a repetition or cause an increment past a representable bound. A loop header that looks familiar is not a proof that its body is safe for every input.
In the continue example, does skipping the addition for value two leave value stuck at two?
Read the explanation
No. For a for loop, continue still leads to its update expression before the next test. The variable advances and the final sum is four.
Primary references and further reading
- WG14 N1570 — public C11 committee draft: Sections 6.8.3–6.8.6 provide the core rules used in this C17-baseline explanation. This is a public draft, not the final ISO publication.
- WG14 N3096 — public C23 draft: Labeled statements and the C23 fallthrough annotation; the baseline loop examples remain C17.
Before you move on
- Conditions choose a path using the state examined at that point.
- A loop trace should show the test, body, update, and exit.
- break, continue, and return transfer control according to different enclosing constructs.
Keep these ideas separate
- break / continue
- break leaves the nearest enclosing loop or switch; continue proceeds to the enclosing loop’s continuation step.
What state would you trace to check whether a loop runs zero, one, or one-too-many times?
Optional: say it aloud or keep a note. You can continue whenever you are ready.Check your understanding
Optional. Answers are not saved or sent, and reading stays unrestricted.
Read the explanation for every choice
- while always runs once before checking.
That is not while’s control rule; its condition is checked before entering the body.
- The compiler removes every loop.
Loop behavior follows the program’s semantics, not a universal removal rule.
- Its controlling expression can be false at the first check.
✓ Correct reasoning. A false initial condition prevents the first body execution.
C17
Quick reference from the earlier edition
This compact reference keeps existing links and saved passages available. Read the expanded lesson above for the full context.
Conditional Branching
if/else handles scalar conditions; switch selects labels using an integer controlling expression (including enumerated types). After a selected case, execution continues through later labels unless control is transferred, for example by break, return, or goto. A final case need not have a redundant break. Document intentional fall-through; C23's [[fallthrough]] annotation documents it and does not itself jump or stop execution.
Loops
for (init; condition; update)groups initialization, a continuation test, and an update when supplied. The initialization can be an expression or a declaration; this form is useful for counted iteration.while (condition)checks its condition before each iteration, so the body may run zero times.do { ... } while (condition);checks its condition after each iteration, guaranteeing the body runs at least once.
Jump Statements
breakexits the nearest enclosing loop orswitch.continuecontinues the nearest enclosing loop. In aforloop it runs the update expression before retesting the condition; inwhileanddo-whileit proceeds to the condition test.goto label;transfers control to a label in the same function, subject to scope restrictions. A common use is a shared cleanup path for releasing resources after errors. That is one useful pattern, not the only possible use of goto. Prefer control structures that make the intended flow clear.
Ready for the next idea?
Mark this chapter as read whenever you feel ready.