Home / Learn Embedded C / Functions and Scope
Functions and Scope
Breaking firmware into small functions, and what "scope" means for a variable.
The idea, explained simply
Definition
A function is a named, reusable block of code; scope is the region of code where a variable's name is valid — local variables exist only inside the function (or block) that declares them.
Why you need this
Breaking GPIO/timer/UART logic into small, well-named functions (like gpio_write(), delay_ms()) is exactly what makes embedded code readable and testable instead of one giant main().
How it works
Local variables are created fresh each time a function runs and destroyed when it returns; global variables live for the entire program and are visible everywhere, which is powerful but easy to misuse.
Where you'll see this
- Driver design
- Code organization
- Unit testing
Try it
Small, single-purpose functions like celsius_to_fahrenheit are easy to test on their own, independent of any hardware.
| Scope | Lifetime | Visible from |
|---|---|---|
| Local (inside a function) | Created and destroyed each call | Only that function/block |
| Global | Entire program run | Any function in the file (or program, if not static) |
| static local | Entire program run, but created once | Only that function (see next lesson) |
Try it: a local variable shadowing a global of the same name
The local counter only exists inside show_local_shadow -- outside it, the global counter is completely untouched. That boundary is exactly what "scope" means.
Test what you just read
1. What happens to a local variable when its function returns?
Local variables live only as long as the function call that created them (ignoring static, covered next).