C++ Core
Control Flow
Branching and loops decide which statements run.
Concept core idea Watch out easy to get wrong
Concept
Key concepts
- Branching (
if/else/switch) and loops (for/while/do-while) direct which statements run. switchneedsbreakin each case or it falls through to the next case.do-whileruns 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.
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.