Control Flow
Challenge Gallery
Quick Reference
C truth values:
| Value | Boolean meaning |
|---|---|
0 |
false |
| Any non-zero | true |
NULL |
false (it’s 0) |
Loop patterns:
| Pattern | When to use |
|---|---|
for (int i = 0; i < n; i++) |
Known number of iterations |
while (condition) |
Unknown iterations, may run zero times |
do { ... } while (condition); |
Must run at least once (input validation) |
The = vs == trap:
if (x = 5) // ASSIGNMENT — always true (assigns 5 to x)
if (x == 5) // COMPARISON — true only when x is 5
switch template:
switch (value) {
case 'A': action_a(); break;
case 'B': action_b(); break;
case 'C':
case 'D': action_cd(); break; // C and D share code (fall-through)
default: action_default(); break;
}
Common Pitfalls
=vs==— Assignment in condition is legal C and almost always a bug. Compile with-Wall.- Dangling else — Without braces,
elseattaches to the nearestif. Always use braces. - Missing break in switch — Causes fall-through to the next case. Intentional fall-through should be commented.
- switch on strings — Not possible in C. Use
if/else ifwithstrcmp(). - Infinite loops — Forgetting to update the loop variable.
while(1)is intentional;while(x > 0)withoutx--is a bug. - Off-by-one in loops —
<=vs<is the most common loop bug. Draw the first and last iterations to verify.