Systems CourseC/C++ · Linux · Memory
C++ CoreLesson 01 of 441 min read6 questions

Control Flow

Branching and loops decide which statements run.

Test yourself ↓

Concept core idea Watch out easy to get wrong

Concept

Key concepts

  1. Branching (if/else/switch) and loops (for/while/do-while) direct which statements run.
  2. switch needs break in each case or it falls through to the next case.
  3. do-while runs the body at least once (condition checked after).
Watch out

Fall-through gotcha

A switch without break keeps running the following cases until a break or the end.

C++
switch(x){
  case 1: doA();      // no break -> also runs case 2!
  case 2: doB(); break;
}
Watch out

Easily confused

while vs do-while
while checks the condition BEFORE the first run (may run 0 times); do-while checks AFTER (runs at least once).
= vs ==
= assigns; == compares. if(x = 5) assigns 5 and is always true — a classic bug.

Test yourself

6 questions on this lesson. Write your answers from memory, then compare them with the model answers side by side.