Home / Learn Embedded C / Functions and Scope

Functions and Scope

Breaking firmware into small functions, and what "scope" means for a variable.

The gistBreaking 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

Breaking logic into small functionsC: edit and run

Small, single-purpose functions like celsius_to_fahrenheit are easy to test on their own, independent of any hardware.

ScopeLifetimeVisible from
Local (inside a function)Created and destroyed each callOnly that function/block
GlobalEntire program runAny function in the file (or program, if not static)
static localEntire program run, but created onceOnly that function (see next lesson)
Careful:Overusing global variables makes embedded code hard to test and full of hidden coupling between functions — prefer passing values as parameters and return values where practical.

Try it: a local variable shadowing a global of the same name

Local variables shadowing a global of the same nameC: edit and run

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?