Functions and scope: copies, lifetime, recursion
Function arguments are passed as copies. The lifetime of local and global variables, and why recursion is avoided on an MCU.
Pass by value
A C function receives a copy of each argument. Changing the argument inside the function leaves the caller's variable untouched. To change the outside value, pass its address. This is the first reason to learn pointers.
Variable lifetime
| Kind | Where | Until when |
|---|---|---|
| Local variable | Stack | Gone when the function returns |
| Global variable | .data / .bss | Until the program ends |
| static local variable | .data / .bss | Until the program ends; the name is visible only inside the function |
If you return the address of a local variable, another function overwrites that memory after the function ends. It compiles, and it is one of the hardest bugs to find.
Why recursion is avoided
Every call adds to the stack. On an MCU with a few KB of RAM, recursion of unpredictable depth leads to stack overflow, and the symptom is a variable with a strange value or a hard fault. Most embedded coding standards forbid recursion.