Constexpr in C++
Short notes on constexpr in C++: how it differs from const, what a constexpr function can do, and what changed in C++14, C++20 and C++23.
constexpr came with C++11 and is still fairly new for many C++ developers. const only means the value can’t be changed after initialization, but the value itself can come at runtime. A constexpr variable must be known at compile time.
int readValue();
const int a = readValue(); // fine, a is read-only but calculated at runtime
constexpr int b = 10 * 4; // calculated at compile time
// constexpr int c = readValue(); // error, not a constant expression
constexpr is generally used in front of a function. Such a function can be calculated at compile time when its arguments are constant expressions, and it still works as a normal function at runtime with runtime values. The return type and the parameters must be literal types (built-in types, references, pointers and simple classes with constexpr constructors), not only primitives. Returning void is allowed since C++14.
constexpr int myfunc(){
return 1;
}
constexpr int square(int x){
return x * x;
}
static_assert(square(4) == 16); // checked by the compiler
int main(){
int n = 5;
int r = square(n); // runtime call, also fine
int arr[square(3)]; // array size known at compile time
}
In C++11 a constexpr function body could only have a single return statement. C++14 relaxed it, so local variables, if and loops are allowed.
constexpr long factorial(int n){
long result = 1;
for (int i = 2; i <= n; ++i)
result *= i;
return result;
}
static_assert(factorial(5) == 120);
Update (2026): It has changed a lot since this note was written in the C++17 days. C++17 added
if constexprand constexpr lambdas. C++20 addedconsteval(the function must run at compile time),constinit, constexpr virtual functions,tryblocks, andnew/deleteinside constant evaluation, sostd::vectorandstd::stringcan be used in constexpr functions. C++23 relaxed more rules, for examplestatic constexprvariables are allowed inside a constexpr function, andstd::unique_ptrbecame constexpr.
consteval int compileTimeOnly(int x){
return x * 2;
}
constexpr int ok = compileTimeOnly(21); // 42
// int n = 21; compileTimeOnly(n); // error, n is not a constant