C Programming · Interview question

Why might a static local variable be dangerous in embedded code?

A strong answer

Because it's not reentrant. A static local is a single shared instance that persists across all calls, so if the function can be entered concurrently, called from both an ISR and the main loop, or from two RTOS tasks, the callers stomp on each other's state. For example, a function using a static buffer to build a string will have one task's data overwritten by another's mid-operation. The same persistence that makes static locals useful (retaining state between calls) makes them a hazard under concurrency, which is the norm in embedded systems with interrupts. The fixes are to pass state in via parameters (caller-owned, so each caller has its own), guard the function with a critical section, or make the function genuinely stateless. This is the same reentrancy concern as returning a pointer to a static buffer.

What a weak answer sounds like

You know the answer. Do you know what gets you dinged?

Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.

From the lesson

const, volatile & static

Three small keywords with outsized consequences: const for intent, volatile for hardware and ISR-shared data, static for lifetime and linkage, and why volatile is not atomic.

More const, volatile & static questions

Browse all 472 interview questions