Lesson 163 +10 XP

Constexpr Functions and Consteval

Constexpr Functions and Consteval

Some work can finish before the program runs. A constexpr function is one the compiler may evaluate at compile time when the arguments are compile-time known. A consteval function must always run at compile time.

A constexpr function

constexpr double sq(double x) {
  return x * x;
}

Call it with a constant and the compiler can substitute the answer directly - no function call in the running program.

When runtime data comes in

using namespace std;

int main() {
  int input;
  cin >> input;
  cout << sq(input) << "\n"; // input is runtime -> runs at runtime
  return 0;
}

With a runtime value, a constexpr function simply runs normally at runtime; compile-time evaluation is only possible when the arguments allow.

Consteval forces compile time

consteval int triple(int x) {
  return x * 3;
}

A consteval function has no runtime presence: it must be evaluated during compilation, and calling it with a runtime-only value is a compile error.

Why compile-time computation rocks

  • The value is computed while the program is built, so runtime is never spent on it.
  • Results can be used where constants are required, like array sizes.
  • Mistakes are caught at build time, not when the program runs.

TL;DR

  • constexpr functions can run at compile time when the arguments allow.
  • With runtime data a constexpr function falls back to runtime.
  • consteval functions are locked to compile time.
  • Calling consteval with runtime-only input causes a compile error.