How do I compute values at compile time with constexpr?

In C++, the `constexpr` keyword allows you to compute values at compile time. This can significantly enhance the performance of your application by reducing runtime computation. When a function or variable is declared as `constexpr`, it tells the compiler to evaluate it at compile time rather than at runtime, provided the input values are also known at compile time.

Here’s an example of how to use `constexpr` to compute a factorial function at compile time:

    #include 

    constexpr int factorial(int n) {
        return (n <= 1) ? 1 : n * factorial(n - 1);
    }

    int main() {
        constexpr int value = factorial(5);
        std::cout << "Factorial of 5 is: " << value << std::endl;
        return 0;
    }
    

In this example, the `factorial` function is declared with `constexpr`, which allows it to be evaluated at compile time. When you run this program, the value of `factorial(5)` is computed during compilation, and thus readily available at runtime.


constexpr compile time C++ performance optimization factorial example