Stackless coroutines for gamedev in ~200 lines of C++
C++20 coroutines, while syntactically elegant, are poorly suited for game development due to issues like heap allocations, opaque state, and lack of serializability. The article presents sfex::Coroutine, a lightweight, stackless coroutine library in about 200 lines of C++ that avoids these pitfalls. It enables allocation-free, serializable, and deterministic coroutines ideal for use in boss scripts, dialogue systems, and AI behaviors.
- ▪C++20 coroutines often perform unpredictable heap allocations, making them unsuitable for real-time game development.
- ▪sfex::Coroutine uses a macro-based switch and __LINE__ technique to enable fully serializable and allocation-free coroutine state.
- ▪The library allows game developers to pause and resume coroutines, making features like mid-cutscene saving straightforward and reliable.
- ▪Unlike standard C++20 coroutines, sfex::Coroutine state is fully visible and inspectable, enabling debugging and deterministic replay.
- ▪The entire implementation is contained in a single small header file, emphasizing simplicity and ease of integration.
Opening excerpt (first ~120 words) tap to expand
stackless coroutines for gamedev in ~200 lines of C++ 01 may 2026 c++ c++20 coroutines C++20 coroutines have lovely1 syntax. They are also a terrible fit for game development.2 If you’ve ever tried to use them for boss scripts, dialogue, or AI behaviors – anywhere you want straight-line code that pauses for a few frames – you’ve probably hit the same wall I did: opaque handles, heap allocations3, hidden compiler lowering, and – most damning for games – no way to serialize a paused coroutine to disk. In this article, I will present sfex::Coroutine: a ~200-line stackless macro-based coroutine library built around a variant of the classic switch + __LINE__ trick. Like my previously discussed sfex::Profiler, these coroutines are meant to be simple and lightweight.
…
Excerpt limited to ~120 words for fair-use compliance. The full article is at Vittorioromeo.