C Control Flow
Challenge Gallery
Quick Reference
Control structures:
// if-else
if (condition) { ... }
else if (other) { ... }
else { ... }
// switch
switch (x) {
case 1: /* ... */ break;
case 2: /* ... */ break;
default: /* ... */ break;
}
// loops
for (int i = 0; i < n; i++) { ... }
while (condition) { ... }
do { ... } while (condition);
Common Pitfalls
- = vs == – Assignment in conditions is a logic bomb. Some use
if (0 == x)to catch it. - Missing break – Fall-through in switch is silent. Always add break unless intentional.
- Off-by-one –
i <= nvsi < nis the source of countless bugs. Think about boundaries. - Infinite loops – Forgetting to update the loop variable. Always check your exit condition changes.
- Dangling else –
if (a) if (b) x; else y;– the else binds to the inner if. Use braces.