lib/unreachable.cpp

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 <iostream>
#include <utility>

void start() {std::cout << "start()\n";}
void run() {std::cout << "run()\n";}
void stop() {std::cout << "stop()\n";}

enum class StateT { open, atwork, done };


void foo(StateT state)
{
  switch (state) {
   case StateT::open:
     start();
     break;
   case StateT::atwork:
     run();
     break;
   case StateT::done:
     stop();
     break;
   default:
    std::unreachable();  // ``dear compiler, this cannot be reached''
  }
}

int main()
{
  foo(StateT::atwork);
  //foo(StateT4); // ERROR: undefined behavior
}