constexpr keyword

The constexpr (constant expression) keyword is used in C++. This keyword is used to declare constants or functions that can be evaluated at compile time. This means the compiler can replace calls to the constexpr function with the result of the function computed at compile time, thus improving the performance of your program.

Example:

constexpr int square(int x) {
    return x * x;
}
 
int main() {
    const int a = square(10);  // This is computed at compile time.
    int b = square(5);  // Even though 'b' is not const, this is still computed at compile time.
    return 0;
}
  • a and b are not actually computed at runtime, their values (100 and 25) are hard-coded into the compiled program by the compiler.

This can lead to performance improvements in your program, as the function doesn’t actually need to be called and computed at runtime.

Note

constexpr only works for functions whose result can be determined entirely at compile time. If the function’s result depends on runtime information (such as input from the user, a value read from a file, etc.), then it cannot be a constexpr function.

Constexpr vs. static?

See static for the answer.