top of page
  • Joseph

C++ constexpr

Updated: Nov 9, 2022

Constexpr is a keyword that declares that the value of a variable or a function is declared at compile time. Similar to the const keyword a compiler error is raised when any code attempts to modify the value of a constexpr. While the value of a const variable can be initialised at run time time the constexpr needs to be initialised at compile time. Const expression is especially useful for template arguments and array declarations.


int main()
    constexpr int a = 10;
    int b = 0;
    constexpr int c = b + 1; // error as b is not a constexper
                             // or a const
    constexpr int d = a + 1; // no error as a is constexpr

A constexpr function is a function whose return value is computed at compile if the code code requires it. It can also function a normal function, that is evaluated at runtime, if the code does not require it.


constexpr int factorial(int n)
    if (n == 0)
        return 1;
        return n * factorial(n - 1);

int main()
    // evaluated at compile time
    char arr[factorial(4)]; 

    // evaluated at run time
    std::cout<< "Factorial(10) " << factorial(10) <<std::endl; 

11 views0 comments

Recent Posts

See All

We can use variadic arguments to create variadic data structures in C++. template<typename ... T> struct DS{}; template<typename T, typename ... Args> struct DS<T, Args ...> { T first; DS<Arg

C++ standard library has simple functions to manipulate types. The following example shows how we can find the type of a variable and create new types using that. int main() { const double A = 10;

A fold expression is an instruction for the compiler to repeat the application of an operator over a parameter pack. This is especially useful when you need to apply the same operator to a set of argu

bottom of page