Control Flow & Functions
Branching, loops, and how C functions pass arguments by value
In a nutshell
if/else, switch, for, while, do/while, break, continue — all present in Java, all present in C with nearly identical syntax. Two C-specific wrinkles matter this week. One, the C90 for loop requires the counter to be declared above the loop (Lab 1 compiles with -std=c90 -pedantic). Two, missing braces around a multi-statement if body is not a style issue; it is the exact bug pattern that produced Apple’s “goto fail” CVE and forged SSL certificate acceptance on every iPhone for two years.
Functions work like Java methods with no class around them. Every argument is copied (pass-by-value), and a function cannot directly modify a caller’s variable. That limitation is what pointers solve next week.
Why it matters
The for-counter rule and switch fall-through both land directly on Lab 1. The missing-braces discipline is the rule that shows up in every professional code review and every static analyzer. Functions and pass-by-value are the foundation for understanding pointers next week: the reason scanf needs &x is exactly because a function cannot otherwise write to the caller’s variable.
Key takeaways
- Always use braces on
if/else/for/whilebodies, even for single-statement bodies. CVE-2014-1266 is why. - C90
forloop declares the counter at the top of the enclosing block:int i; ... for (i = 0; i < n; i++) { ... }. switchfalls through. Missingbreakmeans the next case’s body runs too. This is a bug you will hit once and then never again. Stacked labels (case 'F': case 'f':) are the intentional, Lab 1-friendly use.continueinforruns the step clause.continueinwhiledoes not; if the counter update is in the body aftercontinue, you get an infinite loop.- Functions pass arguments by value. A copy goes into the parameter. The caller’s variable is not modified. To modify the caller, return a new value, or (next week) pass a pointer.
- Prototype before use. If
maincallsaddbutaddis defined below, declareint add(int a, int b);abovemainor get an implicit-declaration warning.
Lessons in this topic
| Lesson | What it covers |
|---|---|
| If/Else, Switch & Loops | Branching, switch fall-through (bug and feature), C90 for, while, do/while, break, continue, the goto-fail walkthrough |
| Functions & Recursion | Prototypes, pass-by-value, scope, recursion, the call stack |
Practice and deep dives
Practice this topic: C Control Flow or C Functions drills, or browse the practice gallery.
For the concrete “goto fail” mechanism and the other four Lab 1 CWEs, see the memory-safety deep dive. For how stack frames hold the parameters and locals of each call (foundation for recursion and for next week’s pointer work), see the machine model deep dive.
What comes next
Pointers — the & operator you have been using with scanf, generalized. Once you have pointers, you can write functions that modify the caller’s variables, walk arrays through arithmetic, and allocate memory on the heap.