co_return is a C++ coroutine statement that completes execution. Used without an expression, it signals completion through the coroutine's promise; unlike an ordinary return, it works with the coroutine machinery supplied by the return type. section 8.3.1 section 8.3.5
Stopping a mind-reader coroutine
A coroutine reading player input can stop when no input remains: `if (!input) { co_return; }`. Otherwise it yields the player's choice and a prediction, suspends, and later resumes with its state intact. section 8.3.2
Use co_return with these coroutine rules:
- Add co_return, co_yield, or co_await to make a function a coroutine, then return a suitable coroutine object such as Task. section 8.3.1 section 8.3.2
- Use a bare co_return with promise_type::return_void(); use co_return expression with promise_type::return_value instead. section 8.3.5
- Let final_suspend mark completion so the returned Task can observe that the coroutine has finished. section 8.3.5
Listing 8.16 Our first coroutine
#include <coroutine>
struct Task; #1
Task coroutine_game() #2
{
std::mt19937 gen{ std::random_device{}() };
std::uniform_int_distribution dist{ 0, 1 };
MindReader mr(gen, dist);
while (true)
{
auto input = read_number(std::cin);
if (!input)
{
co_return; #3
}
int player_choice = input.value();
co_yield{ player_choice , mr.get_prediction() }; #4
mr.update(player_choice);
}
}
Inspect the complete coroutine flow: bare co_return exits on abandoned input, while co_yield pauses before the next iteration. section 8.3.2
