Advertisement
Beginner C++, Coroutines

What is a coroutine in C++20?

Short answer

A coroutine is a function that can suspend its execution and resume later, preserving its local state across suspensions. A function becomes a coroutine if its body uses co_await, co_yield, or co_return.

Save C++ mock interview
Advertisement
AModel answer
A coroutine is a function that can suspend its execution and resume later, preserving its local state across suspensions. A function becomes a coroutine if its body uses co_await, co_yield, or co_return. Coroutines enable writing asynchronous or lazy/generator code in a sequential, readable style instead of callbacks or state machines.
Generator<int> counter() {
    for (int i = 0;; ++i) co_yield i;   // suspends, yielding i
}
Real-world example
An async network handler is written as a coroutine that co_awaits I/O, reading like straight-line code.
Likely follow-ups
  • What three keywords make a coroutine? | What do coroutines enable?
Related topics