Constant Expressions: constexpr
In this lesson, we will see how constexpr is used in modern C++.
Constant expressions #
With constexpr
, we can 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 a lot of advantages.
A constant expression:
- can be evaluated at compile time
- gives the compiler deep insight into the code
- is implicitly thread-safe
- 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 it at compile time. This holds true not only for built-in types but also for instantiations of user-defined types. There are a few serious restrictions for objects in order to evaluate them at compile time.
To make our lives easier, we will use types built into the C++ library like bool
, char
, int
, and double
. We will call the remaining data types user-defined data types. These are all std::string
types. User-defined types typically hold built-in types.
Variables #
By using the keyword, constexpr
, a variable can be made a constant expression.
constexpr double myDouble= 5.2;
Therefore, we can use the variable in contexts that require a constant expression, e.g., defining the size of an array. This has to be done at compile time.
For the declaration of a constexpr
variable, we have to keep a few rules in mind.
The variable: ...