coro/fibo2.hpp

The following code example is taken from the book
C++23 - The Complete Guide by Nicolai M. Josuttis, Leanpub, 2026
The code is licensed under a Creative Commons Attribution 4.0 International License. Creative Commons License

// raw code

#include <utility>
#include <generator>

std::generator<long> fibonacci()
{
  // first two numbers are 1:
  long a = 1;
  long b = 1;
  co_yield a;        // SUSPEND with first number
  co_yield b;        // SUSPEND with second number

  // endless loop over sum of previous two numbers:
  while (true) {
    auto sum = a + b;
    co_yield sum;    // SUSPEND with sum of previous two numbers
    a = std::exchange(b, sum);
  }
}