Constant Expressions: constexpr
In this lesson, we will see the usage and implementation of constexpr in Modern C++.
Constant Expressions
With the keyword constexpr
, we define an expression that can be evaluated at compile time. constexpr
can be used for variables, functions, and user-defined types. An expression that is evaluated at compile time has many advantages.
A constant expression does the following:
- It can be evaluated at compile time.
- It gives the compiler deep insight into the code.
- It is implicitly thread-safe.
- It can be constructed in the read-only memory (ROM-able).
constexpr
- Variables and Objects
If we declare a variable as constexpr
, the compiler will evaluate them at compile time. This holds true both for built-in types and for instantiations of user-defined types. There are a few restrictions for objects in order to evaluate them at compile time.
To make this process easier, we will use built-in types like bool
, char
, int
, and double
. We call the remaining data types as user-defined data types, for example, std::string
, types from the C++ library, and user-defined data types. User-defined types typically hold built-in types.
Variables
By using the keyword constexpr
, the variable becomes a constant expression.
constexpr double myDouble=
...