Error 040
BBC Micro:bit
Severity: CriticalWhat Does This Error Mean?
Error 040 means the Micro:bit's call stack has overflowed. This happens when functions call themselves too deeply (infinite recursion) or when too many nested function calls occur. Simplify your program's function nesting.
Affected Models
- BBC Micro:bit V1
- BBC Micro:bit V2
Common Causes
- Infinite recursion — a function calling itself without a base case
- Too many deeply nested function calls
- Very large local variables in functions consuming stack space
- Event handlers triggering new events recursively
How to Fix It
-
Check for recursive functions that do not have a proper exit condition.
A function that calls itself must have a base case that stops the recursion. Without it, the call stack fills up until it overflows.
-
Convert deep recursion to iteration (use loops instead).
Most recursive algorithms can be rewritten as loops. Loops use constant stack space regardless of the number of iterations.
-
Reduce the size of local variables in functions.
Large arrays or strings declared inside functions consume stack space. Move them to global scope or reduce their size.
-
In MakeCode: avoid nested forever blocks calling functions that trigger events.
Event handlers that trigger other events can create indirect recursion.
Frequently Asked Questions
What is the call stack?
The call stack tracks which functions are currently running and where to return when they finish. Each function call adds a frame to the stack. Too many frames overflows it.
How deep can functions nest on the Micro:bit?
The V1 has very limited stack space (~2KB). The V2 has more (~8KB). Practically, keep function nesting under 10-20 levels.