Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

std::unreachable

Use case

Mark unreachable code for optimization.

Explanation

std::unreachable = UB if reached, but enables certain optimizations (e.g. compiler can eliminate dead code paths).

Code

#include <cstdint>
#include <print>
#include <utility>

enum class Arch { ARM64, X86_64 };

const char *archName(Arch a) {
  switch (a) {
  case Arch::ARM64:
    return "arm64";
  case Arch::X86_64:
    return "x86_64";
  }
  std::unreachable();
}

int main() {
  std::println("{}", archName(Arch::ARM64));
  return 0;
}

View on GitHub.

Output

$ ./src/c++23/build/std-unreachable
arm64