The keyword constexpr is used to show that a constant is resolved at compile time. This is a new keyword introduced with C++11.
Both constexpr and const are used to show that something is constant and the difference is that a constexpr value must be resolved at compile time whereas a const can be resolved at run time or at compile time.
1 2 3 4 5 6 7 8 |
void f() { constexpr double pi = 3.141592; // constant defined at compile time constexpr double two_pi = 2.0 * 3.141; // constant calculated by the compiler at compile time. const int some_value = 4; // ok, const can be used for both run time and compile time constants } |
In most cases there is no real difference between a compile time or a run time constant but in some cases must the constant be defined at compile time. One example is creating fixed size arrays where the size must be a constant defined at compile time:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
void f(const int size) { char userMessage[size]; // does not compile. Run time constant. } void g() { const int size = 512; char message[size]; // compiles. The size is a compile time constant } void h() { int size = 512; char message[size]; // does not compile. The size is not constant } |
constexpr can also be used for function calls
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
int size() { return 5; } constexpr int const_size() { return 5; } void f() { int data[size() + 1]; // this will not compile, size cannot be resolved by compiler int data[const_size() + 1]; // this compiles in C++11, size is compile time constant } |
However, a constexpr function must only consist of a single return statement, only call constexpr functions and only access constexpr global/member variables.
The purpose of constexpr is to replace macros and hard coded literal values without sacrificing performance or type safety.



