The constexpr keyword

 

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.

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:

constexpr can also be used for function calls

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.

Facebookgoogle_pluslinkedinmail