Ground Embedded KO Subscribe

Notes / C Language

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.

GROUND EMBEDDED · NOTEC Language 04Functions and scope 1volatile uint32_t *ODR 2 = (uint32_t*)0x40020014; 3*ODR |= (1u << 5); 4while (1) { 5 if (flag) toggle(); 6}

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.

FREE PDFGet the 3 free ebooksIf you want to keep reading this topic as one book: BLDC motor control, serial communication and sensors at book length. PDFs are in Korean.Get them free →