YOUR C LEARNING COMPANION

Find your next idea.

Learning path
C foundationsChapter 12 of 73

Conditions, choices, and loops

Follow how execution selects a path, repeats work, and transfers control, with careful attention to boundaries and progress.

7 min readFoundationsC17 baseline
Offline reading
In this chapter10 sections
0% through this chapter

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.

C17 · illustrative fragment
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

C17 · illustrative fragment
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

C17 · illustrative fragment
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

C17 · illustrative fragment
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.

C17 · illustrative fragment
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

C17 · illustrative fragment
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.

Think it through

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

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.
Explain it in your own words

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.

Why can a while loop execute its body zero times?
Read the explanation for every choice
  1. while always runs once before checking.

    That is not while’s control rule; its condition is checked before entering the body.

  2. The compiler removes every loop.

    Loop behavior follows the program’s semantics, not a universal removal rule.

  3. 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

  • break exits the nearest enclosing loop or switch.
  • continue continues the nearest enclosing loop. In a for loop it runs the update expression before retesting the condition; in while and do-while it 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.

CHAPTER 12 / 73

In this chapter

Conditions, choices, and loops

Search all 73 chapters in both languages.EN + HG

Try “pointer”, “why int”, or “undefined behavior”.

Concepts connect. Follow your curiosity.↑ ↓ to explore · Enter to open
MAKE YOURSELF COMFORTABLE

Your reading space

Appearance

A clear canvas with balanced contrast.

Text size

100%
AA

Reading tools

Your data stays in this browser

Export a backup before changing browsers or replacing an older version of the reader.

YOUR PERSONAL MARGINS

My notebook

Saved on this device
A LITTLE CLARITY

The glossary

A starting meaning, then a chapter to go deeper.

A QUICK DEFINITION

A little clarity

Read the full explanation →

A thought worth keeping