Advertisement
Beginner C++, Coroutines

What do co_await, co_yield, and co_return do?

Short answer

co_await suspends the coroutine until an awaited operation is ready, then resumes. co_yield suspends and produces a value to the caller (used for generators), resuming on the next request. co_return ends the coroutine, optionally returning a value.

Save C++ mock interview
Advertisement
AModel answer
co_await suspends the coroutine until an awaited operation is ready, then resumes. co_yield suspends and produces a value to the caller (used for generators), resuming on the next request. co_return ends the coroutine, optionally returning a value. These keywords drive the suspend/resume behavior.
Example

co_yield x; // produce a value, suspend co_await task; // wait for async result co_return r; // finish

Real-world example
A lazy sequence generator uses co_yield to produce one element per resumption on demand.
Likely follow-ups
  • Which keyword produces a value lazily? | Which awaits an async result?
Related topics