
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.
#include<iostream>
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.
#include<iostream>
constexpr int factorial(int n)
{
if (n == 0)
return 1;
else
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;
}