0Pricing
C++ Academy · Lesson

constexpr and Compile-Time

Compute values at compile time.

What constexpr Means

constexpr tells the compiler a value or function can be evaluated at compile time, producing a true compile-time constant.

#include <iostream>

int main() {
    constexpr int size = 4 * 4;   // computed at compile time
    int arr[size];
    std::cout << sizeof(arr) / sizeof(int) << "\n";
}

constexpr Functions

A constexpr function can run at compile time when given constant arguments, and at runtime otherwise.

#include <iostream>

constexpr int square(int x) { return x * x; }

int main() {
    constexpr int s = square(5);   // compile time
    int n = 6;
    std::cout << s << " " << square(n) << "\n";  // second at runtime
}

All lessons in this course

  1. const Variables and Parameters
  2. const Member Functions
  3. constexpr and Compile-Time
  4. consteval and constinit
← Back to C++ Academy