What are coroutines in C++20, and how do they differ from standard functions in terms of stack management?
Last updated
A coroutine is a function that can suspend and later resume with its local state preserved. Any function using
co_await,co_yield, orco_returnis a coroutine.C++20 coroutines are stackless: locals and the resume point live in a heap-allocated coroutine frame, not on the call stack. A normal function's frame is popped on return, but this frame persists until resumed or destroyed.
The language supplies only the machinery. A return type with a
promise_type(or a library type likestd::generator) defines suspension behavior, which suits generators and async I/O.